Can someone quickly and simply explain to me how to perform an action every couple of seconds using
var timeOut = setTimeout(FunctionName, 5000);
I want to run a function every 5 seconds.
The setInterval() method calls a function at specified intervals (in milliseconds). The setInterval() method continues calling the function until clearInterval() is called, or the window is closed. 1 second = 1000 milliseconds.
Answer: Use the JavaScript setInterval() method You can use the JavaScript setInterval() method to execute a function repeatedly after a certain time period. The setInterval() method requires two parameters first one is typically a function or an expression and the other is time delay in milliseconds.
The setInterval() method in JavaScript can be used to perform periodic evaluation of expression or call a JavaScript function.
As you asked for a method using setTimeout
:
function doStuff() {
console.log("hello!");
setTimeout(doStuff, 5000);
}
setTimeout(doStuff, 5000);
But it would probably be better to use setInterval
:
function doStuff() {
console.log("hello!");
}
setInterval(doStuff, 5000);
Just put setTimeout
at the end inside your function, with a call to itself - like a delayed tail-recursion.
Use setInterval
:
var timeOut = setInterval(nextNotice, 5000);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With