Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call JavaScript function after 1 second One Time

Tags:

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);  
like image 236
BLK Horizon Avatar asked May 29 '14 23:05

BLK Horizon


People also ask

How do you call a function after 1 sec?

To delay a function execution in JavaScript by 1 second, wrap a promise execution inside a function and wrap the Promise's resolve() in a setTimeout() as shown below. setTimeout() accepts time in milliseconds, so setTimeout(fn, 1000) tells JavaScript to call fn after 1 second.

Which JavaScript function is used to call a function once after a certain time?

Answer: Use the JavaScript setInterval() method You can use the JavaScript setInterval() method to execute a function repeatedly after a certain time period.

Can I call a function multiple times JavaScript?

In order to run a function multiple times after a fixed amount of time, we are using few functions. setInterval() Method: This method calls a function at specified intervals(in ms). This method will call continuously the function until clearInterval() is run, or the window is closed.

How do you run a function every 5 seconds in JavaScript?

To call a JavaScript function every 5 seconds continuously, we call setInterval with the function that we want to run and the interval between runs. const interval = setInterval(() => { // ... }, 5000); clearInterval(interval); to call setInterval with the callback we want to run and 5000 millisecond period.


1 Answers

If it needs to run just once you can use setTimeout

setTimeout(function () {   console.log('Hello world') }, 1000)  setTimeout(() => {   console.log('Foo bar') }, 1000)
like image 134
Cjmarkham Avatar answered Oct 08 '22 00:10

Cjmarkham