To repeat a function indefinitely, setTimeout can be called recursively:
Unlike setInterval, this ensures that the function will execute even if the function's running time is longer than the specified delay. However, it does not guarantee a regular interval between function executions. This behaviour also varies because an exception before the recursive call to setTimeout will prevent it from repeating again, while setInterval would repeat indefinitely regardless of exceptions.
You don't need to create the variable, but it's a good practice as you can use that variable with clearInterval to stop the currently running interval
If you need to pass parameters to the doSomething function, you can pass them as additional parameters beyond
the first two to setInterval.
setInterval, as above, will run every 5 seconds (or whatever you set it to) no matter what. Even if the function doSomething takes long than 5 seconds to run. That can create issues. If you just want to make sure there is that pause in between runnings of doSomething, you can do this:
window.setInterval() returns an IntervalID, which can be used to stop that interval from continuing to run. To do this, store the return value of window.setInterval() in a variable and call clearInterval() with that variable as the only argument:
This will log This will be logged every 5 seconds every 5 seconds, but will stop it after 32 seconds. So it will log the message 6 times.
window.setTimout() returns a TimeoutID, which can be used to stop that timeout from running. To do this, store the return value of window.setTimeout() in a variable and call clearTimeout() with that variable as the only argument:
This will not log the message because the timer is stopped after 3 seconds.
setTimeout, order of operations, clearTimeout
Syntax : setTimeout(function, milliseconds) or window.setTimeout(function, milliseconds)
This example outputs "hello" to the console after 1 second. The second parameter is in milliseconds, so
1000 = 1 sec, 250 = 0.25 sec, etc
Order of operations
Also, zero milliseconds here does not mean the function inside the setTimeout will execute immediately. It will take slightly more than that depending upon the items to be executed remaining in the execution queue. This one is just pushed to the end of the queue.
Cancelling a timeout
clearTimeout() : stops the execution of the function specified in setTimeout()
Syntax : clearTimeout(timeoutVariable) or window.clearTimeout(timeoutVariable)