One-time scheduling
Run deferred work once after a delay.
Node.js · Module
Node.js timers schedule callbacks for later execution through the event loop. Use setTimeout, setInterval, or setImmediate, and cancel scheduled work with the matching clear function.
The timers module schedules callbacks through Node.js's event loop. Use setTimeout for one execution, setInterval for repeated execution, or setImmediate for execution after the current poll phase; each returns a handle that can be cancelled with its matching clear function.
setTimeout(callback[, delay[, ...args]])
setInterval(callback[, delay[, ...args]])
setImmediate(callback[, ...args])
clearTimeout(timeout)
clearInterval(interval)
clearImmediate(immediate)| Name | Type | Description |
|---|---|---|
callback | Function | Function invoked when the timer fires. |
delay | number | Delay in milliseconds before execution; the documentation's timer APIs accept a delay value. |
args | any[] | Optional values passed as arguments to the callback. |
setTimeout(), setInterval(), and setImmediate() return timer objects that can be passed to their corresponding clear functions.
const timeout = setTimeout(() => {
console.log('finished');
}, 1000);
setTimeout(() => clearTimeout(timeout), 500);Schedules a callback, then cancels it before the one-second delay expires.
Run deferred work once after a delay.
Repeat polling, cleanup, or heartbeat logic.
Defer work until a later event-loop phase.
Prevent pending callbacks after shutdown or state changes.
setTimeout schedules a callback for one execution after a delay, while setInterval schedules repeated executions at the specified interval. Both return timer objects that can be cancelled with clearTimeout or clearInterval.
Follow-up: How would you stop a recurring interval? Store the object returned by setInterval and pass it to clearInterval.
setImmediate schedules a callback for immediate execution in a later event-loop phase. It is distinct from a zero-delay timeout, whose ordering can depend on the event-loop context.
Follow-up: Why might their order vary? Node.js processes these callbacks through different event-loop phases, so surrounding I/O and phase state affect ordering.
The timer functions are global, so importing node:timers is not required for ordinary use. The module is still the documented source for these APIs and can be imported when explicit module access is preferred.
Follow-up: What alternative supports Promise-based timer workflows? Use node:timers/promises, which exposes timer functions that return Promise objects.
setTimeoutclearTimeoutsetIntervalclearIntervalsetImmediateclearImmediatenode:timers/promises