Skip to content
jshacks.dev
Async

Node timers promises setTimeout setInterval scheduler wait

Learn the node:timers/promises module in Node.js 24, with awaitable setTimeout, async-iterable setInterval, setImmediate, scheduler.wait and cancellation.

6 min read
Summarize in AI
Flat illustration of jobs on a conveyor heading to a rack of workers, with the Node.js, JavaScript, Apache Kafka and Redis logos.

Wrapping setTimeout in a promise is a four-line helper that every Node.js codebase has written at least once, usually with slightly different names and no way to cancel it. The standard library ships a better version. The node:timers/promises module exports setTimeout, setInterval, setImmediate and a scheduler object, all promise-based, all accepting an AbortSignal. This post covers each export with the exact output in Node.js 24, how cancellation works, how the async-iterable setInterval replaces a callback loop, and the small traps around resolved values and unref.

The import

JavaScript
import {
  setTimeout as sleep,
  setInterval as every,
  setImmediate as nextTurn,
  scheduler,
} from "node:timers/promises";

Renaming on import avoids clashing with the global functions of the same names. In CommonJS use require("node:timers/promises") in the same way.

Awaiting a delay

setTimeout(delay, value, options) returns a promise that resolves with value after delay milliseconds. Note the argument order: the delay comes first, and there is no callback.

JavaScript
import { setTimeout as sleep } from "node:timers/promises";

console.log("start");
const result = await sleep(100, "done waiting");
console.log(result);
Text
start
done waiting

The second argument is optional and becomes the resolved value. A small convenience, but it keeps chains short: await sleep(50, data) passes data through after a pause.

Cancelling with AbortSignal

The options object takes a signal. Aborting rejects the promise with an AbortError, and clears the timer so the process is not kept alive.

JavaScript
import { setTimeout as sleep } from "node:timers/promises";

const controller = new AbortController();

const pending = sleep(5000, "never", { signal: controller.signal });

setTimeout(() => controller.abort(), 50);

try {
  await pending;
} catch (error) {
  console.log(error.name, error.code);
}
Text
AbortError ABORT_ERR

This is the main reason to prefer the module over a hand-written helper: the cancellation path is correct, and it composes with other APIs that accept signals, such as fetch.

JavaScript
import { setTimeout as sleep } from "node:timers/promises";

async function withTimeout(task, ms) {
  const timer = new AbortController();
  const timeout = sleep(ms, "timed out", { signal: timer.signal });
  try {
    return await Promise.race([task, timeout]);
  } finally {
    timer.abort();
  }
}

const value = await withTimeout(sleep(20, "fast result"), 1000);
console.log(value);
Text
fast result

Aborting the timer in finally clears it when the task wins the race. The aborted timeout promise rejects, but nothing is awaiting it any more, so you should attach a handler or make sure that Promise.race already consumed it. Here Promise.race subscribed to it, so its later rejection is handled.

Keeping the process alive or not

By default the timer keeps the event loop alive. Set ref: false so the timer does not prevent the process from exiting, for example a background heartbeat that should not hold the program open.

JavaScript
import { setTimeout as sleep } from "node:timers/promises";

sleep(60_000, "never seen", { ref: false }).then(console.log);
console.log("main work finished");
Text
main work finished

Nothing else is pending, so the process exits at once, without waiting a minute. Without ref: false the program would sit there for 60 seconds.

setInterval as an async iterator

The promise version of setInterval(delay, value, options) returns an async iterator that yields value once per interval. You consume it with for await, and break stops the interval.

JavaScript
import { setInterval as every } from "node:timers/promises";

let count = 0;

for await (const tick of every(50, "tick")) {
  count += 1;
  console.log(tick, count);
  if (count === 3) break;
}

console.log("loop ended");
Text
tick 1
tick 2
tick 3
loop ended

This replaces a setInterval plus clearInterval pair. The timer is cleared when the loop exits, whether by break, return or a thrown error. A loop body is never entered twice at once, since for await pulls the next tick only after the current iteration ends.

JavaScript
import { setInterval as every } from "node:timers/promises";

const controller = new AbortController();
setTimeout(() => controller.abort(), 130);

try {
  for await (const _ of every(50, undefined, { signal: controller.signal })) {
    console.log("poll");
  }
} catch (error) {
  console.log("stopped:", error.name);
}
Text
poll
poll
stopped: AbortError

The signal ends the loop by throwing an AbortError from the iterator, so wrap the loop in try and catch when you use it. Ticks at 50 and 100 ms fit before the abort at 130 ms.

setImmediate

setImmediate(value, options) resolves in the check phase of the event loop. It is a way to yield to I/O inside a long async loop.

JavaScript
import { setImmediate as nextTurn } from "node:timers/promises";

let sum = 0;

for (let i = 1; i <= 6; i++) {
  sum += i;
  if (i % 3 === 0) await nextTurn();
}

console.log(sum);
Text
21

Every third iteration yields to the loop, so other callbacks can run during a long computation. Pick the chunk size for your own workload by measuring.

scheduler.wait and scheduler.yield

The module also exports a scheduler object that follows the Web Scheduling API. scheduler.wait(delay, options) behaves like setTimeout(delay) without a value, and scheduler.yield() is equivalent to setImmediate().

JavaScript
import { scheduler } from "node:timers/promises";

await scheduler.wait(50);
console.log("waited");
await scheduler.yield();
console.log("yielded");
Text
waited
yielded

Both accept { signal } as well. The Node.js documentation marks scheduler.wait and scheduler.yield as experimental, so check the status for your version before relying on them in a library. Their value is portability: the same names exist in browsers that implement the Scheduler API.

Comparison with the callback timers

TaskCallback stylePromise style
DelaysetTimeout(fn, ms)await sleep(ms)
CancelclearTimeout(handle)AbortSignal
RepeatsetInterval and clearIntervalfor await (... of every(ms))
Errors in the callbackuncaught exceptionnormal try and catch
Return valuea Timeout objecta promise

The last row is the quiet benefit. Code after an awaited delay is part of the async function, so its errors propagate to the caller instead of crashing the process from inside a timer callback.

Common mistakes

Swapping the argument order. The callback API is (fn, ms) and this API is (ms, value). Passing a function as the delay resolves to a type error.

**Forgetting to handle AbortError.** An aborted sleep rejects. Catch it where the cancellation is expected.

Leaking a long timer. A sleep with a long delay that is no longer needed keeps the process alive. Abort it, or use ref: false.

Using it in the browser. The module exists only in Node.js. Browsers have no built-in promise timers, so write a small sleep there.

Replacing a hand-written sleep helper

Most codebases already contain a function that looks like const sleep = (ms) => new Promise((r) => setTimeout(r, ms)). It works, and it lacks three things that the standard module gives you. It cannot be cancelled, so a sleep that is no longer needed keeps a timer alive and keeps the process from exiting. It cannot be told not to keep the process alive, which matters for background heartbeats. And it cannot be combined with the cancellation signals that the rest of the platform uses. Replacing the helper with the module's setTimeout removes these gaps in one import, and your tests gain the ability to abort a pending wait rather than wait for it.

Using it in tests

Promise timers pair well with test runners. A test that needs to wait for a debounce interval can await a promise timer, and the runner's fake timers can still advance it, since the module is built on the same timer machinery. If you use the built-in node:test runner, its mock timers can intercept the promise versions too, so a test about retry delays finishes instantly. Check the documentation of your runner for the exact list of supported functions, because coverage of the promise API has grown across releases.

Polling with an async iterator

The async iterator form of setInterval is a good fit for polling a resource until a condition holds. The loop reads like a description of the task: for each tick, check the status, and stop when it is ready. Because leaving the loop clears the timer, there is no cleanup code to forget, and wrapping the whole loop in a try and catch handles both an abort and an error from the check itself. Add a limit on the number of ticks or a signal with a timeout, so a resource that never becomes ready cannot keep the loop alive forever.

Also inNode.js
Share

Keep reading

Flat illustration of a package parcel arriving from Composer, with the Node.js, Yarn, pnpm and GitHub logos.
Node.js

How require() Resolves Modules

Follow the CommonJS resolution algorithm in Node.js step by step, from core modules and relative paths to node_modules lookups, package exports and caching.

6 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.