setTimeout()
When writing JavaScript code, you might want to delay the execution of a function.
This is the job of setTimeout. You specify a callback function to execute later, and a value expressing how later you want it to run, in milliseconds:
setTimeout returns a Timeout instance in Node.js, whereas in browsers it returns a numeric timer ID. This object or ID can be used to cancel the scheduled function execution:
Zero delay
If you specify the timeout delay to0, the callback function will be executed as soon as possible, but after the current function execution:
Some browsers (IE and Edge) implement a
setImmediate() method that does this same exact functionality, but it’s not standard and unavailable on other browsers. But it’s a standard function in Node.js.setInterval()
setInterval is a function similar to setTimeout, with a difference: instead of running the callback function once, it will run it forever, at the specific time interval you specify (in milliseconds):
clearInterval, passing it the interval id that setInterval returned:
clearInterval inside the setInterval callback function, to let it auto-determine if it should run again or stop. For example this code runs something unless App.somethingIWait has the value arrived:
Recursive setTimeout
setInterval starts a function every n milliseconds, without any consideration about when a function finished its execution.
If a function always takes the same amount of time, it’s all fine.
Maybe the function takes different execution times, depending on network conditions for example. And maybe one long execution overlaps the next one.
To avoid this, you can schedule a recursive setTimeout to be called when the callback function finishes:
setTimeout and setInterval are available in Node.js, through the Timers module.