Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 133 ยท The Runtime

Timers

Master Node.js timers - setTimeout, setInterval, setImmediate, clearing, unref and ref, the promise-based timers module, scheduler.wait, drift and AbortSignal.timeout.

Almost every real program needs to say "do this later" or "do this every few seconds": retry a failed request after a pause, expire a cache entry, send a heartbeat, give up on a slow operation. Node.js has had timers since its first release, and the API is familiar from browsers: setTimeout, setInterval, setImmediate and their clear counterparts. Modern Node adds a promise-based module that lets you simply await a delay.

This lesson covers the whole timer toolbox and the subtle promises each tool makes (and does not make): when a callback runs, what keeps your process alive, why intervals drift, and how to put a deadline on any operation. It builds on The Event Loop; read that first if "timers phase" is unfamiliar.

setTimeout and clearTimeout

setTimeout(callback, delay, ...args) schedules callback to run once, at least delay milliseconds from now. Any extra arguments are passed to the callback, so you do not need a wrapper function. The call returns a Timeout object (not a number, unlike in browsers) that you can pass to clearTimeout to cancel.

Node.js Scheduling, passing arguments and cancelling

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.

The script's last line prints first, then the timer fires. Notice that Node keeps the process running until pending timers are done; you did not have to do anything to wait for them.

Delays are minimums, never promises

A timer says "not before this time", and nothing more. The callback runs when the event loop reaches the timers phase and the time has elapsed. If the thread is busy with other work, it runs late; it never runs early (apart from rounding of at most about a millisecond). Delays are also clamped: values below 1 become 1, which is why setTimeout(fn, 0) and setTimeout(fn, 1) behave the same. Delays above 2,147,483,647 ms (about 24.8 days) overflow a 32-bit integer and are reset to 1 ms, with a warning like this (shown here as plain text, because it goes to the error stream):

TEXT
(node:12345) TimeoutOverflowWarning: 2147483648 does not fit into a 32-bit signed integer.
Timeout duration was set to 1.

Negative delays and NaN are treated the same way, with a TimeoutNegativeWarning. For long waits, store a due date and check it on a shorter timer instead of one huge delay.

Ordering guarantees

Timers fire in order of their due times. If two timers have the same delay and were created in sequence, the first created fires first. If a short timer is created after a long one, the short one still fires first when due.

Node.js Timers fire in due-time order

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.

You get the 20 ms pair in creation order (A then B), then the 40 ms timer, then the 60 ms one. Ordering is only guaranteed for timers whose due times differ meaningfully or that share a delay; do not build logic on timers that are 1 ms apart.

setInterval

setInterval(callback, delay) is like setTimeout that re-arms itself and keeps calling callback every delay ms until you call clearInterval. Forgetting to clear an interval is a classic cause of processes that never exit.

Node.js An interval that stops itself

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.

You can call clearInterval from inside the callback, as above. Because setTimeout and setInterval objects are interchangeable for clearing purposes in Node, clearTimeout(interval) also works, but use the matching name for readability.

Drift and overlapping work

An interval counts from the moment each callback was scheduled, but if the loop is busy or the callback itself is slow, runs can bunch up or fall behind. Two problems follow:

  • Drift. Interval callbacks are not exactly delay ms apart: each run can be a little late, and a long block of the event loop delays everything after it. Never use an interval to keep time; compare against a clock instead.
  • Overlap. An interval never waits for async work. If the callback starts a request that takes longer than the delay, the next run starts while the previous one is still in flight.

When each run depends on the previous one finishing, chain setTimeout calls instead. The next delay then starts after the work is done:

Node.js A self-scheduling loop that never overlaps

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.

With setInterval(poll, 10) and 25 ms of work, about three runs would be in flight at the same time. With the self-scheduling pattern, never more than one. Use it for polling, retries and anything that must not overlap.

setImmediate

setImmediate(callback, ...args) runs the callback in the check phase of the current loop turn, after pending I/O. It is not a timer in the sense of time at all: it means "as soon as the loop has handled I/O". Use it to yield to the loop in the middle of long work (see the chunking example in The Event Loop). Cancel it with clearImmediate.

setImmediate and setTimeout(fn, 0) are not interchangeable: from the main script their relative order is not defined. From inside an I/O callback setImmediate is always first.

ref and unref: what keeps the process alive

A running timer normally keeps Node alive, because the process only exits when there is nothing left to wait for. Sometimes that is wrong. Think of a background cleanup timer in a library: it should not prevent the application from exiting when everything else is done.

timeout.unref() tells Node "do not let this timer keep the process alive". timeout.ref() undoes it, and timeout.hasRef() tells you the current state.

Node.js An unref'd timer does not keep the process alive

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.

The program ends right after the 20 ms timer, without waiting a minute. If the unref'd timer were the only thing left, Node would exit immediately and its callback would never run. That is the point: it is "optional" background work.

Another handy method is timeout.refresh(), which restarts the timer's countdown with its original delay and returns the same object. It is the cheapest way to build an inactivity timeout: call refresh() whenever activity happens, and the callback only fires after a quiet period.

Node.js refresh() as an inactivity timeout

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.

The idle timer would have fired after 40 ms, but each refresh() pushed it back. Only when the activity stops does it fire. This is cheaper than creating a new timer for every event, which matters for servers with many connections.

The promise-based timers module

Wrapping setTimeout in a promise by hand is so common that Node ships it ready-made in node:timers/promises. It exports promise versions of setTimeout, setImmediate and setInterval, plus a scheduler object.

Node.js await a delay with timers/promises

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.

sleep(ms, value) resolves with the optional second argument after ms milliseconds. scheduler.wait(ms) is the same but without the value. The async-iterator form of setInterval yields the value on every tick and fits naturally into async code, with ordinary try/catch around the loop. Breaking out of the for await loop cleans up the interval.

A one-line const sleep = (ms) => new Promise(r => setTimeout(r, ms)) still works fine and you will see it everywhere. The built-in version supports cancellation with an AbortSignal and does not need to be copied into every project.

Cancelling and timeouts with AbortSignal

Both sleep and the other promise timers accept { signal }. When the signal aborts, the promise rejects with an AbortError and the timer is cleared. Pair this with AbortSignal.timeout(ms), which creates a signal that aborts itself after a delay, and you can put a deadline on anything that understands signals.

Node.js Cancelling a sleep, and a signal that aborts itself

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.

Two details to remember. First, when a promise timer is cancelled by AbortSignal.timeout, the error is an AbortError whose cause is the TimeoutError; the signal's own reason is the TimeoutError. Second, AbortSignal.timeout timers are unref'd internally, so an unused timeout signal never keeps your process alive. Signals are covered fully in AbortController and Cancellation; fetch, file reads and streams accept them too.

Racing a timeout against slow work

When an API does not support signals, you can still limit how long you wait by racing the work against a timer. Note that this does not stop the underlying work; it only stops you from waiting for it.

Node.js Giving up on slow work after a deadline

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.

The first call wins the race. The second hits the 50 ms deadline and rejects with our error. The finally block cancels the timer that did not fire; without it, a lingering timer would keep the process alive longer than needed. (When the loser is the timer, aborting it makes it reject with an AbortError; because Promise.race has already settled, that late rejection is ignored.)

Practical advice

  • Always keep the handle if you may need to cancel. A timer you cannot clear is a leak waiting to happen.
  • Clear intervals when the thing they serve goes away (a closed connection, a stopped server). Prefer unref() for housekeeping timers in libraries.
  • Do not trust precision. Timers are for "about this long", not for scheduling to the millisecond. For measuring elapsed time use performance.now(), which is monotonic; Date.now() can jump when the system clock is adjusted.
  • Prefer promises in new code. await sleep(ms) reads better and cancels cleanly.
  • Guard against exceptions. An error thrown in a timer callback is an uncaught exception that can crash the process; the callback has no surrounding try/catch from the code that created it. See Errors and Error Handling.
  • Mind this. Timer callbacks written as function get this bound to the Timeout object, not to your class; use arrow functions or .bind.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does the delay passed to setTimeout guarantee?

    The delay is a minimum. The callback runs when the loop reaches the timers phase and the time has elapsed, which can be later.
  2. 2. What does timer.unref() do?

    An unref'd timer still fires if the process is still running, but on its own it will not stop Node from exiting.
  3. 3. Why use a self-scheduling setTimeout instead of setInterval for polling with async work?

    setInterval fires on schedule regardless of whether the previous run finished. Scheduling the next setTimeout after the work ends prevents overlap.
  4. 4. What happens when you await sleep(10000, null, { signal }) from node:timers/promises and the signal is aborted?

    Promise timers honour AbortSignal: aborting rejects the promise with AbortError and releases the timer.
  5. 5. Which statement about setTimeout(fn, 0) versus setImmediate(fn) called from the main script is correct?

    From the main script the order depends on how quickly the loop starts. Only inside an I/O callback is setImmediate guaranteed to win.

Summary

  • setTimeout runs a callback once after at least the delay; setInterval repeats; setImmediate runs in the loop's check phase. Each has a matching clear function.
  • Delays below 1 ms become 1 ms; delays above about 24.8 days overflow and are reset to 1 ms with a warning.
  • Timers fire in due-time order; equal delays keep creation order.
  • unref() lets the process exit even if the timer is pending; ref() restores the default; refresh() restarts a timer cheaply, which is ideal for inactivity timeouts.
  • Use a self-scheduling setTimeout when runs must not overlap; setInterval does not wait for async work.
  • node:timers/promises provides awaitable setTimeout, setImmediate, setInterval (as an async iterator) and scheduler.wait, all cancellable with AbortSignal.
  • AbortSignal.timeout(ms) creates a signal that aborts itself, giving any signal-aware API a deadline.

Next: The process Object