Timers (Node.js)
Node.js timers schedule code to run later: setTimeout runs once after a delay, setInterval runs repeatedly, and setImmediate runs after the current event-loop phase. Each returns a handle you can cancel.
Node.js
Timers let you defer or repeat work. setTimeout(fn, ms) runs fn once after at least ms milliseconds; setInterval(fn, ms) runs it every ms until cleared; and setImmediate(fn) runs fn on the next iteration of the event loop, after I/O callbacks of the current phase.
Delays are a minimum, not a guarantee: a busy event loop can push a timer past its requested time, because the loop only fires timers between other work. So setTimeout(fn, 0) does not run immediately — it runs after the current synchronous code and microtasks finish.
Each timer function returns a handle you cancel with the matching clear function (clearTimeout, clearInterval, clearImmediate). process.nextTick and Promise microtasks run before timers. The timers/promises module offers Promise-based versions for use with await.
Syntax
const id = setTimeout(fn, ms); clearTimeout(id);Examples
JavaScript
const id = setInterval(() => console.log("tick"), 1000);
setTimeout(() => {
clearInterval(id);
console.log("stopped");
}, 3500);Output:
tick
tick
tick
stopped