Node.js Reference ยท Globals and Console
Node.js setInterval() function
Reference for setInterval() in Node.js: repeat a callback, stop it with clearInterval, avoid overlapping work and drift, and use the async iterator version.
setInterval(callback, delay, ...args) calls callback again and again, with roughly delay milliseconds between the starts of each call. It returns a Timeout object; pass it to clearInterval() to stop the repetition.
An interval keeps the Node.js process alive until you clear it. Forgetting to do so is the most common reason a script "hangs" after its work is finished.
const timer = setInterval(() => console.log('tick'), 1000);
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.
Syntax
setInterval(callback[, delay[, ...args]]): Timeout // node:timers/promises setInterval([delay[, value[, options]]]): AsyncIterator
| Name | Description |
|---|---|
callback |
Function called on every repetition. |
delay |
Milliseconds between calls. Defaults to 1; clamped like setTimeout(). |
...args |
Extra arguments passed to callback each time. |
value |
(promise version) The value yielded on every tick. |
options |
(promise version) signal to cancel and ref to control whether it keeps the process alive. |
Returns: a Timeout object.
Errors: ERR_INVALID_ARG_TYPE if callback is not a function.
Usage notes
- Always have a stop condition. Keep the handle and call
clearInterval()(orunref()the timer for background work such as a metrics flush). - Drift: the next run is scheduled relative to the previous scheduled time, but a busy event loop can delay runs. Ticks never run in parallel on one thread, though a delayed interval may fire late and not catch up for every missed tick.
- Overlap with async work:
setIntervaldoes not wait for a promise returned by an async callback. If a run can take longer than the delay, use a self-reschedulingsetTimeoutas shown above. - Unhandled rejections: an
asynccallback that rejects is not caught by the timer; catch errors inside it. - The async iterator version applies backpressure for free: if the loop body is slow, ticks are not queued up forever. Leave the loop with
breakor anAbortSignalto stop it. - Clearing from inside the callback is safe. The next call is simply not scheduled.
- Interchangeable clears:
clearTimeout()also stops an interval in Node.js, but useclearInterval()for readability. - Testing: real intervals make tests slow. Mock timers (see Mocking and timers) let you advance time instantly.