Skip to content
jshacks.dev
Async

AbortSignal.timeout and AbortSignal.any

Learn how AbortSignal.timeout adds a deadline to any cancellable call and how AbortSignal.any combines several signals, with exact behavior on Node.js 24.

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

Two static methods on AbortSignal turn cancellation from something you wire by hand into something you compose. AbortSignal.timeout(ms) returns a signal that aborts itself after a delay, which gives any API that takes a signal a deadline in one line. AbortSignal.any(signals) returns a signal that aborts as soon as any of the given signals does, so you can combine a user's cancel button, a timeout and a shutdown signal into one. Both are in Node.js 24 and current browsers, and they remove the manual timer, the clearTimeout and the listener plumbing that used to surround every cancellable request. This post shows how each one behaves, with printed output, what the abort reason is in each case, how they interact with fetch and with your own code and the points where they surprise people. It builds on the AbortController post.

AbortSignal.timeout

JavaScript
const signal = AbortSignal.timeout(20);

console.log("aborted at start:", signal.aborted);

await new Promise((resolve) => setTimeout(resolve, 40));

console.log("aborted later:", signal.aborted);
console.log("reason name:", signal.reason.name);
Text
aborted at start: false
aborted later: true
reason name: TimeoutError

The signal aborts itself after 20 ms, and its reason is a DOMException named TimeoutError, not AbortError. That distinction is useful, since it lets a handler tell "the user cancelled" from "we gave up waiting".

Use it with fetch to give a request a deadline.

JavaScript
try {
  await fetch("https://example.com/slow", { signal: AbortSignal.timeout(2000) });
} catch (error) {
  if (error.name === "TimeoutError") {
    console.log("request took too long");
  } else {
    throw error;
  }
}
Text
request took too long

This assumes the server fails to answer within two seconds. When it does answer in time, the request completes normally and the timer does nothing. There is no timer to clear and no listener to remove, which is the main improvement over the Promise.race timeout, which has to clear its timer or keep the process alive.

What the timer does and does not keep alive

The timer behind AbortSignal.timeout does not keep the Node.js process running. If the only thing left is the pending timeout, the process exits and the signal never fires.

JavaScript
const signal = AbortSignal.timeout(5000);
signal.addEventListener("abort", () => console.log("never printed"));

console.log("script ends here");
Text
script ends here

The program ended immediately and did not wait five seconds. That is the right behavior for a deadline on other work, since a deadline should never be the reason a process stays alive.

AbortSignal.any

AbortSignal.any takes an iterable of signals and returns one that aborts when the first of them does, with the same reason.

JavaScript
const user = new AbortController();
const shutdown = new AbortController();

const combined = AbortSignal.any([
  user.signal,
  shutdown.signal,
  AbortSignal.timeout(1000),
]);

combined.addEventListener("abort", () => {
  console.log("combined aborted, reason:", combined.reason.message);
});

shutdown.abort(new Error("server is shutting down"));
Text
combined aborted, reason: server is shutting down

The first source to abort decides the reason, and later aborts of the others change nothing. If any input is already aborted when any is called, the combined signal is aborted immediately with that reason.

JavaScript
const already = AbortSignal.abort(new Error("born aborted"));
const combined = AbortSignal.any([already, new AbortController().signal]);

console.log(combined.aborted, combined.reason.message);
Text
true born aborted

AbortSignal.abort(reason) is the third static helper, which creates a signal that is already aborted. It is convenient for tests and for passing a cancelled state through an API.

The common combination: cancel or time out

A button should cancel a request, and the request should also have a deadline. Before any, you wrote both listeners yourself. Now it is one expression.

JavaScript
function request(url, { signal, timeoutMs = 5000 } = {}) {
  const signals = [AbortSignal.timeout(timeoutMs)];
  if (signal) signals.push(signal);

  return fetch(url, { signal: AbortSignal.any(signals) });
}

const cancel = new AbortController();

setTimeout(() => cancel.abort(new Error("user pressed cancel")), 10);

try {
  await request("https://example.com/slow", { signal: cancel.signal });
} catch (error) {
  console.log(error.message);
}
Text
user pressed cancel

The user's cancel won because it arrived before the deadline. Had the deadline been first, the rejection would have been a TimeoutError, and the caller could show a different message. This function composes: callers pass their own signal, and the function adds its own deadline without taking over the caller's control.

Using signals in your own code

Both kinds of signals work with the checking style from the earlier post: signal.throwIfAborted() at checkpoints, or listening to the abort event.

JavaScript
async function slowSum(numbers, { signal }) {
  let total = 0;

  for (const n of numbers) {
    signal.throwIfAborted();
    await new Promise((resolve) => setTimeout(resolve, 10));
    total += n;
  }

  return total;
}

try {
  await slowSum([1, 2, 3, 4, 5, 6, 7, 8], { signal: AbortSignal.timeout(35) });
} catch (error) {
  console.log(error.name, "after partial work");
}
Text
TimeoutError after partial work

The throwIfAborted call throws the reason, so the function rejects with a TimeoutError. Eight steps of 10 ms need about 80 ms, and the deadline was 35 ms, so the function stopped after three or four steps. The exact count depends on timer accuracy, and only the error is deterministic.

A deadline is not a cancellation of the work behind it

Like any signal, a timeout asks politely. If the code receiving it ignores the signal, nothing stops. A promise raced against AbortSignal.timeout can reject while the underlying operation continues. Make sure that what you pass the signal to actually listens, which fetch, fs.promises functions, timers/promises, child_process.exec, stream.pipeline and events.once all do.

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

try {
  await sleep(1000, null, { signal: AbortSignal.timeout(15) });
} catch (error) {
  console.log(error.name);
}
Text
TimeoutError

Here, the sleep itself stopped, because timers/promises listens for the signal, and the rejection carries the timeout reason.

Surprises

Memory and lifetime. A signal created by AbortSignal.any keeps listeners on its sources while it is alive. Current implementations hold the sources weakly, so a dropped combined signal can be garbage collected, but a long-lived source such as an application-wide shutdown signal that you combine thousands of times creates thousands of dependents until each is collected. Create combined signals per operation, and let them go.

A signal is single use. Once aborted, always aborted. You cannot reset a timeout signal. For a retry, create a fresh AbortSignal.timeout for each attempt.

Timeout starts at creation. The countdown starts when you call AbortSignal.timeout, not when the request starts. Create it right before use. A signal created at module load and used minutes later is already aborted.

Fake timers. Test frameworks that mock setTimeout do not control the internal timer of AbortSignal.timeout in all versions, so tests of timeout behavior should either use a short real delay or construct an AbortController and abort it by hand with a TimeoutError.

Fallbacks

In an older runtime, AbortSignal.timeout can be approximated with a controller and a timer that is unreferenced, so it does not keep the process alive.

JavaScript
function timeoutSignal(ms) {
  const controller = new AbortController();
  const timer = setTimeout(
    () => controller.abort(new DOMException("The operation timed out.", "TimeoutError")),
    ms,
  );
  timer.unref?.();
  return controller.signal;
}

console.log(timeoutSignal(10) instanceof AbortSignal);
Text
true

AbortSignal.timeout has been available since Node.js 17.3 and AbortSignal.any since Node.js 20.3, so on Node.js 24 neither fallback is needed.

Choosing deadlines

A deadline should come from the behavior you want when the dependency is slow. For a user-facing request, pick the longest delay a person will tolerate, often a few seconds, and show a useful message when it passes. For a background job, a longer deadline is fine, but it should still exist, because a job that never times out can hang a worker forever. For a chain of calls, remember that deadlines add up: three sequential calls with five second deadlines can take fifteen seconds in the worst case. Pass one signal for the whole operation with AbortSignal.timeout created at the start, so the total is bounded, and add per-call deadlines only where a single step needs a tighter limit, combining them with AbortSignal.any.

Log timeouts with the name of the dependency and the configured limit. When the same deadline fires often, the limit is probably wrong or the dependency is unhealthy, and the log is how you tell the difference. Retrying after a timeout needs care, since the original request may still be running on the server. Retry only operations that are safe to repeat, and use a new signal for each attempt.

Share

Keep reading

Flat illustration of an editor window full of code, with the Google Chrome, JavaScript and npm logos.
Browser

script Tags: async, defer and type=module

Compare classic, async, defer and module script tags: when each downloads, when each runs, how order is kept and which one to pick for each kind of script.

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.