The Three Timer Functions
Node.js provides the same setTimeout and setInterval functions available in browsers, plus a Node-specific setImmediate. All three schedule a callback to run asynchronously, later.
setTimeout and clearTimeout
Console Output
Click “Run” to see the console output here.
setInterval and clearInterval
Console Output
Click “Run” to see the console output here.
Timer Functions Compared
| Function | Behavior |
|---|---|
| setTimeout(fn, ms) | Runs fn once, after at least ms milliseconds |
| setInterval(fn, ms) | Runs fn repeatedly, roughly every ms milliseconds |
| setImmediate(fn) | Runs fn on the next event loop iteration, after I/O callbacks |
The Delay is a Minimum, Not a Guarantee
setTimeout(fn, 0) does not run fn immediately — it schedules fn for the next timers phase, which only happens once the currently executing synchronous code (and any pending microtasks) finish. Under heavy load, the actual delay can be noticeably longer than requested.
A Non-Blocking Delay Helper
Console Output
Click “Run” to see the console output here.
Best Practice
Always keep a reference to a timer if you might need to cancel it — an interval left running with no way to clear it is a classic source of memory leaks in long-running Node.js processes.