Periodic background work
Run recurring maintenance such as polling or refreshing cached data at a fixed cadence.
Node.js · Function
setInterval repeatedly invokes a callback at a specified millisecond delay. It returns a Timeout handle that can be passed to clearInterval to stop future invocations.
setInterval schedules a callback to run repeatedly, waiting the specified number of milliseconds between scheduled executions. It returns a Timeout object, which can be supplied to clearInterval when the repeated work should stop; optional arguments are passed to each callback invocation.
setInterval(callback[, delay[, ...args]])| Name | Type | Description |
|---|---|---|
callback | Function | Function invoked whenever the interval timer elapses. |
delay | number | Milliseconds to wait before invoking the callback; defaults to 1. |
...args | any | Optional values passed to the callback each time it runs. |
<Timeout> for use with clearInterval().
let count = 0;
const interval = setInterval(() => {
console.log(++count);
if (count === 3) clearInterval(interval);
}, 100);Prints three values at roughly 100-millisecond intervals, then cancels the returned timer.
Run recurring maintenance such as polling or refreshing cached data at a fixed cadence.
Drive a bounded demonstration, retry loop, or heartbeat until a stopping condition is reached.
Pass stable configuration values to each callback without rebuilding the timer callback's surrounding state.
setInterval(callback[, delay[, ...args]]) schedules repeated callback execution every delay milliseconds and returns a Timeout usable with clearInterval. The callback receives any additional arguments supplied to setInterval.
Follow-up: How should an interval be stopped? Store its returned Timeout and call clearInterval with that object when the work is complete.
The callback is invoked repeatedly according to the requested delay, while the timer remains scheduled. The delay is measured in milliseconds and defaults to 1 when omitted.
Follow-up: What happens for a negative delay? Node.js sets it to 1 millisecond, as it does for values below 1.
The function is a global timer API, so it can be called without importing node:timers. Its callback parameter is the function invoked whenever the timer elapses.
Follow-up: How can callback data be provided without closing over it? Add values after delay; Node.js passes those values to every callback invocation.
clearIntervalsetTimeoutsetImmediateTimeout