Node.js Reference ยท Events and Timers
Node.js timers/promises setInterval() function
Reference for setInterval() from node:timers/promises: an async iterator that yields a value every interval, how to stop it and how it handles slow loops.
setInterval(delay, value, options) from node:timers/promises returns an async iterator. Each iteration waits for the next tick and then yields value. You consume it with for await, and you stop it by leaving the loop (break, return, a throw) or by aborting a signal.
Unlike the callback setInterval(), there is no timer object to clear and ticks never pile up on top of a slow loop body: the next interval is scheduled only after you ask for the next value.
import { setInterval as every } from 'node:timers/promises'; for await (const tick of every(100, 'tick')) { break; }
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
import { setInterval } from 'node:timers/promises'; setInterval([delay[, value[, options]]]): AsyncIterator<any>
| Name | Description |
|---|---|
delay |
Milliseconds between ticks. Default 1. |
value |
Value yielded on every tick. Default undefined. |
options.signal |
An AbortSignal. Aborting makes the pending iteration reject with AbortError. |
options.ref |
Boolean, default true. With false, the timer does not keep the process alive. |
Returns: an async iterator (and async iterable). The iterator never finishes by itself.
Errors: AbortError thrown from the for await when the signal aborts. Invalid argument types throw ERR_INVALID_ARG_TYPE.
Usage notes
- The sequence is infinite. Always have an exit:
break, a counter, or an abort signal. Leaving the loop calls the iterator'sreturn()and clears the timer. - The loop body runs between ticks. If the body takes longer than
delay, ticks that came due meanwhile are delivered as soon as you ask for the next value, so do not use it as a precise clock. - The first value arrives after one
delay, not immediately. For "run now, then repeat", do the first piece of work before the loop. - Because iteration is sequential, work inside the body never overlaps with itself, which removes a classic callback
setInterval()bug (overlapping runs of a slow job). - Abort rejects the next pending step. A signal that is already aborted makes the first iteration reject.
- Added in Node.js 15.9.