Call JavaScript function after 1 second One Time

BLK Horizon picture BLK Horizon · May 30, 2014 · Viewed 33.6k times · Source

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); 

Answer

Carl Markham picture Carl Markham · May 30, 2014

If it needs to run just once you can use setTimeout

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

setTimeout(() => {
  console.log('Foo bar')
}, 1000)