skip to content

In Node.js, how do setTimeout and setInterval from node:timers/promises take an AbortSignal, and what happens when the signal aborts?

level: middleimportance: should knowfreq 35%

answer

  1. promises instead of callbacks
  2. an options object with signal
  3. AbortError with code ABORT_ERR
  4. for await over the interval

basics

~20 s

Both take { signal } in their options. setTimeout(delay, value, { signal }) returns a promise; aborting clears the timer and rejects it with an AbortError. setInterval returns an async iterator; aborting stops it, and the for await loop throws that AbortError.

solid answer

~40 s

`node:timers/promises` exports promise versions of the timer functions. `setTimeout(delay, value, options)` and `setImmediate(value, options)` return promises that fulfil with `value`, and `setInterval(delay, value, options)` returns an async iterator consumed with `for await`. Each accepts `options.signal`. When the signal aborts, Node clears the underlying timer and rejects with an `AbortError` whose `code` is `'ABORT_ERR'` and whose `cause` is the signal's `reason`; a signal that is already aborted rejects at once. For `setInterval`, aborting ends the iteration with that error, and breaking out of the loop also clears the interval. So a job scheduler's polling loop stops cleanly on shutdown: abort one controller and treat `AbortError` as the normal exit. `options.ref: false` works like `unref()`.

code

javascript · 19 lines
javascript
const { setInterval: every, setTimeout: sleep } = require('node:timers/promises');

async function drainOnce() {
  await sleep(100); // stand-in for real work
}

async function pollJobs(signal) {
  try {
    for await (const _ of every(1_000, undefined, { signal })) {
      await drainOnce();
    }
  } catch (err) {
    if (err.name !== 'AbortError') throw err; // abort is the normal way out
  }
}

const controller = new AbortController();
pollJobs(controller.signal).then(() => console.log('poller stopped'));
setTimeout(() => controller.abort(), 3_500);

go deeper

for a junior

Know that node:timers/promises gives awaitable timers, that each accepts a signal, and that aborting rejects with an AbortError you usually catch and ignore.

for a middle

Explain the details: the error's code and cause, immediate rejection for an already-aborted signal, timer clean-up on abort and on break, and the ref option.

for a senior

Show how you would wire one shutdown signal through every polling loop and wait, and how missed interval ticks behave when the loop body runs long.

for a principal

Argue for a convention: every long-running loop and wait accepts a signal, so shutdown is one abort call rather than a hunt for timers to clear.

## Promise-based timers in Node `node:timers/promises` exports timer functions that return promises instead of taking callbacks. They graduated from experimental several release lines ago and are the natural way to wait inside `async` code: | Function | Returns | Settles with | |---|---|---| | `setTimeout(delay, value, options)` | a promise | `value`, after `delay` ms | | `setImmediate(value, options)` | a promise | `value`, in the next check phase | | `setInterval(delay, value, options)` | an async iterator | `value`, once per tick | | `scheduler.wait(delay, options)` | a promise | equivalent to `setTimeout(delay, undefined, options)`; Experimental | Each `options` object takes two keys: **`signal`**, an `AbortSignal` that cancels the wait, and **`ref`**, which defaults to `true`; `false` means the timer does not keep the event loop alive. ## How cancellation works - **Already aborted:** if `signal.aborted` is true when you call the function, the promise rejects at once and no timer is created. - **Aborted while waiting:** Node clears the underlying timer and rejects the promise with an **`AbortError`**. - **The error's shape:** `err.name` is `'AbortError'`, `err.code` is `'ABORT_ERR'`, and `err.cause` is the signal's `reason`, so you can tell a shutdown from a deadline. - **Clean-up:** the abort listener is removed once the promise settles, so a long-lived signal does not collect listeners from finished waits. - **Scope:** aborting cancels the timer only. Work you started elsewhere is not stopped unless it watches the same signal. ## Stopping a polling loop with `setInterval` The promise `setInterval` returns an async iterator, which suits a job scheduler that polls for work and must stop cleanly on shutdown: 1. Each tick of the interval lets one iteration of `for await` proceed. 2. Ticks that fire while the loop body is still running are counted, and the iterator yields them afterwards one after another; they are not dropped. 3. A `break` or `return` inside the loop ends the iterator, and its clean-up clears the interval. 4. Aborting the signal clears the interval. If the loop is waiting for the next tick, that wait rejects with an `AbortError`; if the body is running, the next step of the iterator throws it. ```js const { setInterval: every } = require('node:timers/promises'); async function pollJobs(signal, drainOnce) { try { for await (const _ of every(1_000, undefined, { signal })) { await drainOnce(); } } catch (err) { if (err.name !== 'AbortError') throw err; // abort is the normal way out } } ``` Shutdown code then calls `controller.abort()` once, and every loop or wait built on that signal ends. ## Differences from the callback API - **The delay is validated.** The promise functions require a number and reject with `ERR_INVALID_ARG_TYPE` for, say, the string `'1000'`; the global `setTimeout` coerces it instead. - **The same delay rules apply.** A delay below 1 still becomes 1 ms, because the promise versions build the same internal `Timeout` object. - **A value replaces arguments.** The promise fulfils with `value`; there is no list of extra callback arguments. - **The signal is the handle.** There is no `clearTimeout` call for a promise timer; you cancel through `signal`. - **`ref: false` mirrors `unref()`.** An unref'd wait that is the only thing left lets the process exit, and the promise never settles. ## Mistakes that show up in review - **Not catching the `AbortError`.** An abort is the expected way for these loops to end, but an uncaught rejection is still an unhandled rejection; catch it and check `err.name` before rethrowing anything else. - **Passing the signal to the timer only.** The wait is cancelled, but a request or query started inside the loop body keeps running unless it receives the same signal. - **Swallowing every error.** A bare `catch {}` around the loop hides real failures from the work itself; filter on `AbortError` and let the rest propagate. - **Using `ref: false` on a loop that must keep the process up.** If the poller is the process's main job, an unref'd interval lets the process exit as soon as nothing else is pending. ## Where other timeout patterns belong Racing a timer promise against an operation is a language-level pattern, covered with JavaScript retry and timeout helpers. Giving an outgoing HTTP request a deadline with `AbortSignal.timeout(ms)` is covered with calling HTTP services. This leaf's concern is the timer itself: how Node schedules it, cancels it and decides whether it keeps the process alive.

  • What happens if the polling loop body takes longer than the interval?
    The promise `setInterval` keeps counting ticks that fire while the body runs, and once the body finishes the iterator yields those missed ticks one after another without waiting. If back-to-back runs are unwanted, wait with the promise `setTimeout` after each run instead, so the gap is measured from the end of the work.
  • How do you tell a shutdown abort from a deadline abort when both use AbortError?
    Read `err.cause`. Node creates the `AbortError` with the signal's `reason` as its cause, so passing a distinct reason to `controller.abort(reason)` for shutdown, or combining signals with `AbortSignal.any`, lets the catch block tell them apart without parsing messages.

  • Aborting the signal resolves the promise early with undefined
  • The timer keeps running after abort and fires later anyway
  • timersPromises.setTimeout coerces a string delay the way the global one does
  • Breaking out of for await over setInterval leaves the interval running
  • An aborted promise timer rejects with ERR_OUT_OF_RANGE