30

I have successfully managed to make a div hide on click after 400 milliseconds using a setInterval function. My issue is that it runs continually, I only need the function to execute once. After a quick search I discovered that the setInterval can be stopped by clearInterval. Am I using this incorrectly? The closeAnimation function is being executed on click. I modelled my code after the code on this page: http://www.w3schools.com/jsref/met_win_setinterval.asp

function closeAnimation() {
    setInterval(function(){hide()}, 400);
    clearInterval(stopAnimation);
}

var stopAnimation = setInterval({hide()}, 400); 
BLK Horizon
  • 391
  • 1
  • 3
  • 7
  • 8
    Rather than use `setInterval()`, use `setTimeout()`. Timeout runs only once after however many miliseconds. – pp19dd May 29 '14 at 23:16
  • 1
    [MDN: window.setTimeout](https://developer.mozilla.org/en-US/docs/Web/API/Window.setTimeout) – user247702 May 29 '14 at 23:16
  • As Stijn and Carl said, use MDN (Mozilla Developer Network). They have great documentation for all kinds of web developing, and they do not focus on just Mozilla vendor (i.e. "moz" prefixed functions and attribtues) – Patrick Roberts May 29 '14 at 23:19

2 Answers2

74

If it needs to run just once you can use setTimeout

setTimeout(function () {
  console.log('Hello world')
}, 1000)

setTimeout(() => {
  console.log('Foo bar')
}, 1000)
Cjmarkham
  • 9,484
  • 5
  • 48
  • 81
7

You should use setTimeout():

setTimeout(function() {
    getScore(); 
    getResult(); 
}, 1800000);

The '1800000' is the time in milliseconds after which you want this function to execute. In this case, 30 minutes.

Cjmarkham
  • 9,484
  • 5
  • 48
  • 81
betrice mpalanzi
  • 1,436
  • 12
  • 16