Using AbortSignal.any to Compose Timeout and Cancellation Signals in fetch

Using AbortSignal.any to Compose Timeout and Cancellation Signals in fetch

pr0h0••18 min read•coding
AI Usage (75%)
On this page

Introduction: one fetch request, multiple reasons to cancel

A single fetch call often has two independent reasons to stop: it can take too long, and the user can change their mind. This post shows how to use AbortSignal.any() in JavaScript to compose a timeout signal and a user-cancellation signal into one fetch signal that also protects the response body read. In review I keep seeing a Promise.race against a rejecting setTimeout; it reads cleanly and breaks under load.

AbortSignal.any() is the API that fixes this. It takes several signals and returns one composite signal that aborts when the first of them aborts, carrying that signal's reason through. Combined with AbortSignal.timeout() and a per-operation AbortController, it gives you a single signal for the whole request lifecycle — headers and body.

What this fetch cancellation walkthrough builds

One complete, runnable browser example: a Load button, a Cancel button, a status line, and a same-origin endpoint that can delay both its headers and its body. The operation composes a five-second timeout with a user-cancellation controller into one signal, passes it to fetch, and keeps that same signal protecting await response.json().

I'll show the exact files, the expected output for the four cancellation cases (plus a 404 check), and a separate assertion script that pins down the signal semantics without a browser in the loop.

The technical position: compose signals, don't race fetch against a timer

Compose cancellation signals; do not race fetch against a rejection-only timer.

// Don't do this.
const deadline = new Promise((_, reject) =>
  setTimeout(() => reject(new Error("timeout")), 5000)
);
const response = await Promise.race([fetch("/api/slow"), deadline]);

Three concrete problems with that snippet:

  1. The request keeps running. Promise.race settles the outer promise; it does not stop the fetch. The socket stays open, the response arrives, and nothing consumes or releases it.
  2. The body is unprotected. Even if the race "times out", the subsequent response.json() has no deadline at all.
  3. The failure is anonymous. new Error("timeout") is indistinguishable from a TypeError you threw yourself. AbortSignal.timeout produces a DOMException named TimeoutError, which you can branch on.

There's a boundary here, and it gets its own section: client-side cancellation is not a rollback. Aborting a fetch tells the client to stop waiting. It does not tell the server to stop working, and it does not un-commit a database write.

How AbortSignal.any composes timeout and cancellation signals

Three APIs, three jobs: controller, timeout, and composite signal

APIJobProduces
new AbortController()Create cancellation you control.signal + .abort(reason)
AbortSignal.timeout(ms)Create a signal that aborts on its ownA signal, no controller
AbortSignal.any(signals)Combine signals into oneA composite signal, no controller

The composite is read-only from your side — there is no .abort() on it. To cancel a composed operation you abort one of the sources, usually the controller you made for that operation. That keeps ownership explicit instead of letting three layers abort the same handle.

First abort wins, and the reason is preserved by identity

When one input aborts, the composite aborts with that signal's reason. Same object, not a copy or wrapper. If you abort a controller with your own error, the caught rejection is that object and instanceof works.

Later aborts from other sources don't change the reason. The first one won.

Already-aborted inputs, ordering, and the empty iterable

Three edge cases matter if you write a fallback, because the fallback has to reproduce all three:

  • An already-aborted input short-circuits. AbortSignal.any([live, dead]) returns an already-aborted signal synchronously.
  • Iterable order breaks ties. If several inputs are already aborted, the first in iteration order supplies the reason.
  • An empty iterable never aborts. AbortSignal.any([]) is a valid, permanently-live signal.

The spec also throws a TypeError if any element is not an AbortSignal, so a bad array fails loudly instead of silently producing a signal that never fires.

Ownership rules for composed abort signals

Aborting one source does not abort its siblings. Your timeout firing does not flip controller.signal.aborted to true, and Cancel does not cancel the timeout. Each source stays independent; only the composite reflects the union.

Controllers are one-shot. Once abort() has been called, controller.signal.aborted stays true. Reusing that controller for a new request gives you a request that rejects immediately. My rule: one controller per operation, created fresh, discarded after — and a different controller for the replacement request.

Build a complete fetch operation with timeout and user cancellation

The demo server: delay headers and body independently

A few small files, no dependencies. Start with a Node server that serves the page and provides an endpoint whose headers and body can be delayed independently — that is what makes the "cancel after headers" case observable.

server.mjs
// Node 20+. Run with: node server.mjs



const here = (p) => new URL(p, import.meta.url);

const server = createServer(async (req, res) => {
const url = new URL(req.url, "http://localhost:8787");

if (url.pathname === "/") {
  res.writeHead(200, { "content-type": "text/html; charset=utf-8" });
  res.end(await readFile(here("./index.html"), "utf8"));
  return;
}

if (url.pathname === "/api/slow") {
  const headerDelay = Number(url.searchParams.get("headers") ?? 0);
  const bodyDelay = Number(url.searchParams.get("body") ?? 0);
  const started = performance.now();

  res.on("close", () => {
    console.log(
      "[server] socket closed at " +
        Math.round(performance.now() - started) + " ms"
    );
  });

  setTimeout(() => {
    res.writeHead(200, { "content-type": "application/json" });
    res.write('{"slow":'); // headers are out, body is not

    setTimeout(() => {
      res.end("true}");
      console.log(
        "[server] body finished at " +
          Math.round(performance.now() - started) + " ms"
      );
    }, bodyDelay);
  }, headerDelay);

  return;
}

res.writeHead(404, { "content-type": "application/json" });
res.end('{"error":"not found"}');
});

server.listen(8787, () => console.log("http://localhost:8787"));
index.html
<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <title>abort demo</title>
</head>
<body>
  <button id="load">Load</button>
  <button id="cancel" disabled>Cancel</button>
  <pre id="status">idle</pre>
  <script type="module" src="./app.js"></script>
</body>
</html>

The client: one composed signal for fetch and response body

app.js
const loadBtn = document.querySelector("#load");
const cancelBtn = document.querySelector("#cancel");
const statusEl = document.querySelector("#status");

const TIMEOUT_MS = 5000;

// A reason the app owns. We never have to guess from a DOMException name.
class CancelledByUser extends Error {
name = "CancelledByUser";
}

let nextId = 1;
let active = null; // { id, controller }

function render(op, text) {
if (!active || active.id !== op.id) return; // stale write guard
statusEl.textContent = "#" + op.id + " " + text;
}

async function load() {
// 1. Stop the previous operation with *its own* controller.
if (active) active.controller.abort(new Error("superseded"));

// 2. Fresh controller, fresh id, every single time.
const op = { id: nextId++, controller: new AbortController() };
active = op;

// 3. One composed signal for the whole operation.
const signal = AbortSignal.any([
  op.controller.signal,
  AbortSignal.timeout(TIMEOUT_MS),
]);

loadBtn.disabled = true;
cancelBtn.disabled = false;
render(op, "loading");

try {
  const response = await fetch("/api/slow?headers=1500&body=4000", { signal });

  // Evidence for the "headers arrived, body still pending" case.
  console.log(
    "#" + op.id + " headers at " + Math.round(performance.now()) +
      " ms, status " + response.status
  );

  // 4xx/5xx resolve normally. The signal does not make them rejections.
  if (!response.ok) throw new Error("HTTP " + response.status);

  // The body read is still covered by the same `signal`.
  const body = await response.json();
  render(op, "ok " + JSON.stringify(body));
} catch (error) {
  render(op, "failed: " + describe(error));
} finally {
  if (active && active.id === op.id) {
    active = null;
    loadBtn.disabled = false;
    cancelBtn.disabled = true;
  }
}
}

function describe(error) {
if (error instanceof CancelledByUser) return "cancelled by user";
if (error?.name === "TimeoutError") return "timeout after " + TIMEOUT_MS + " ms";
if (error?.name === "AbortError") return "aborted without a custom reason";
if (error?.name === "SyntaxError") return "invalid JSON: " + error.message;
if (error?.name === "TypeError") return "network failure: " + error.message;
return (error?.name ?? "Error") + ": " + (error?.message ?? String(error));
}

loadBtn.addEventListener("click", load);
cancelBtn.addEventListener("click", () => {
active?.controller.abort(new CancelledByUser());
});

The timeout boundary is the whole operation, not just the fetch

The composed signal goes to fetch, and the Fetch Standard ties the response body stream to that signal. So await response.json() is covered too: if the timeout fires mid-body, the body read rejects with the same TimeoutError. That is what the Promise.race version fails to give you.

The other boundary is just as sharp: the signal protects fetch work. It does not protect work you do after parsing. Sorting ten thousand rows, writing to IndexedDB, rendering a canvas — none of that observes the signal automatically. If you need a deadline that spans post-processing, call signal.throwIfAborted() at the boundaries you care about, or check elapsed time yourself.

HTTP failures are not fetch rejections

A 404 or 500 resolves the promise with response.ok === false. Only network-level failures (TypeError) and aborts (the signal's reason) reject. Conflating those is the most common bug here, because it turns a real 500 into "cancelled" in the UI. Check response.ok and throw your own error explicitly.

Restore UI state in finally, and guard against stale writes

Two guards, doing different jobs:

  • op.id !== active.id in render stops an older operation's late rejection from overwriting a newer operation's status. Without it, clicking Load twice quickly shows the first request's timeout under the second request's id.
  • The finally block checks the same condition before re-enabling buttons, so a superseded operation cannot re-enable a control the new operation disabled.

finally still runs on the cancellation path, so the buttons always recover.

Distinguish cancellation reasons from real fetch failures

Built-in abort reasons and a custom cancellation reason

TriggerRejection valuename
AbortSignal.timeout(ms) firesDOMExceptionTimeoutError
controller.abort() with no argumentDOMExceptionAbortError
controller.abort(customReason)customReasonwhatever you set

Modern engines reject the fetch with the signal's reason itself. Older behaviour (pre-2022-ish) always produced an AbortError regardless of what you passed to abort(). If you support old targets, check name as well as identity.

For user cancellation, I use a dedicated Error subclass rather than a bare AbortError DOMException. instanceof CancelledByUser survives message rewording and does not collide with the platform's no-argument abort reason. So AbortError in describe() means unexplained abort — a bug signal, not a normal path.

Inspect the signal, but don't diagnose from it

You can read signal.aborted and signal.reason after a failure. That is useful for telemetry and for logging which source won. It is not a diagnosis.

The response arrives, response.json() throws a SyntaxError on malformed JSON, and the timeout fires two milliseconds later. By the time catch runs and you inspect signal.aborted, it is true — but the failure had nothing to do with cancellation. Diagnose from the caught value first: instanceof, then name, then fall through to a generic message. Use signal.reason to explain which cancellation it was, never whether there was one.

Preserve network and JSON errors

TypeError from fetch (DNS failure, connection reset, CORS) and SyntaxError from json() are real failures with real messages. Pass them through. A generic "request cancelled" on a broken endpoint costs someone an afternoon.

⚠️

Cancelling a request does not undo work the server already did. If the request triggered a write, assume the write happened until you can prove otherwise.

Verify cancellation behavior with reproducible checks

Run the demo locally

node --version          # expect v20.3.0 or newer for AbortSignal.any
node server.mjs         # prints http://localhost:8787

Open http://localhost:8787 in a browser whose compatibility table lists AbortSignal.any. Keep devtools open — the headers at … ms log line is what separates scenario 2 from scenario 4.

Four cancellation scenarios and one HTTP failure

The outputs below are expected output, written from the code above. I label them expected rather than captured because exact milliseconds depend on your machine.

#SetupActionExpected status lineExpected console
1URL ends headers=0&body=0Click Load#1 ok {"slow":true}#1 headers at ~0 ms, status 200
2URL ends headers=6000&body=0Click Load, wait#1 failed: timeout after 5000 msno headers line
3URL ends headers=1500&body=4000Click Load, then Cancel within 1 s#1 failed: cancelled by userno headers line
4URL ends headers=500&body=8000Click Load, wait 6 s#1 failed: timeout after 5000 ms#1 headers at ~500 ms, status 200
5Change the fetch URL to /api/nopeClick Load#1 failed: Error: HTTP 404n/a

Scenario 4 proves the boundary: the headers line printed, so fetch resolved, and then the body read rejected with TimeoutError. A Promise.race implementation would hang for the full eight seconds.

Scenario 3 repeated with headers=6000 should show the same cancelled by user message — the 5 s timeout cannot fire first because the user aborted at ~1 s.

Watch the server console during scenario 4. The body-finish log still appears even though the browser gave up. That is the practical demonstration of the server-side limit.

💪

Verify reason identity in the console: after scenario 3, log active before it is nulled, or temporarily add console.log(error) to the catch. You should see a CancelledByUser object, not a DOMException.

Deterministic signal-level assertions

Browser timing is noisy. Pin the semantics separately with Node's assert module:

signal-checks.mjs
// Run with: node signal-checks.mjs  (Node >= 20.3)


// 1. Empty iterable: a signal that never aborts.
assert.equal(AbortSignal.any([]).aborted, false);

// 2. Already-aborted inputs short-circuit; iterable order breaks the tie.
const first = AbortSignal.abort(new Error("first"));
const second = AbortSignal.abort(new Error("second"));
assert.equal(AbortSignal.any([first, second]).reason.message, "first");
assert.equal(AbortSignal.any([second, first]).reason.message, "second");

// 3. The composite adopts the reason object itself, not a copy.
const reason = new Error("user cancelled");
const user = new AbortController();
const composite = AbortSignal.any([user.signal, new AbortController().signal]);
user.abort(reason);
assert.equal(composite.aborted, true);
assert.equal(composite.reason, reason);

// 4. Later aborts do not replace the winning reason.
const a = new AbortController();
const b = new AbortController();
const combined = AbortSignal.any([a.signal, b.signal]);
a.abort(new Error("first"));
b.abort(new Error("second"));
assert.equal(combined.reason.message, "first");

// 5. Aborting one source leaves its siblings alone.
const x = new AbortController();
const y = new AbortController();
const both = AbortSignal.any([x.signal, y.signal]);
x.abort(new Error("x"));
assert.equal(x.signal.aborted, true);
assert.equal(y.signal.aborted, false);
assert.equal(both.aborted, true);

// 6. Non-signal members throw.
assert.throws(() => AbortSignal.any([{}]), TypeError);

// 7. The timeout signal's reason name is TimeoutError.
const timed = AbortSignal.timeout(10);
await new Promise((resolve) =>
timed.addEventListener("abort", resolve, { once: true })
);
assert.equal(timed.reason.name, "TimeoutError");

console.log("all signal checks passed");

Expected output: all signal checks passed. Check 7 waits on a real 10 ms timer; that is deliberate, so the script is not purely synchronous.

Handle lifecycle and timing traps in fetch cancellation

Reusing an AbortController is the classic bug

const controller = new AbortController(); // module scope — tempting, wrong

async function load() {
  const signal = AbortSignal.any([controller.signal, AbortSignal.timeout(5000)]);
  return fetch(url, { signal }); // rejects instantly after the first abort
}

Once aborted, that controller is dead forever. There is no reset. Create a new one per operation, and cancel the old operation with its own controller before creating the replacement. My load() does exactly that: active.controller.abort(...) first, then new AbortController(). Two objects, two jobs.

There is a second, subtler reason for identity tokens. Without the op.id !== active.id guard, a superseded request's rejection still lands in catch and still writes to the DOM. The guard has nothing to do with the network; it is UI bookkeeping.

AbortSignal.timeout is a timer, not a wall-clock guarantee

Do not describe a five-second timeout as "the request will fail after five seconds of wall clock time". The DOM Standard specifies the timeout in terms of the surrounding timer infrastructure, and browsers throttle or suspend timers in background tabs and frozen pages. A 5,000 ms timeout on a backgrounded tab is not a promise that 5,000 ms of real time elapsed.

Practically: treat the timeout as "the timer fired", not "five seconds passed". If your application needs a hard deadline — an SLA-bound retry budget, for instance — record performance.now() at the start and check elapsed time yourself at the boundaries that matter. I have not benchmarked the divergence across engines, and the exact throttling behaviour is browser-specific; measure it in your target environment if the distinction affects you.

Also note that AbortSignal.timeout cannot be cleared early. When the request finishes early, the timer still fires later and aborts a signal nobody is watching. Harmless, but the timer's lifetime is not tied to your request.

Abort is cooperative

signal stops fetch work. It does not stop unrelated promises, and it certainly does not stop a synchronous loop. If you fan out to worker calls, IndexedDB reads, or a for loop over thousands of items, insert explicit checkpoints:

for (const row of rows) {
  signal.throwIfAborted(); // throws signal.reason if aborted
  await applyRow(row);
}

throwIfAborted() throws the signal's reason, so your catch sees the same TimeoutError or CancelledByUser it would have seen from fetch. That consistency is worth preserving.

The server does not stop when the client aborts

An aborted fetch closes the client's side. The server may notice the socket close — my demo server logs it — and it may not, depending on when the disconnect happens relative to the write. Either way:

  • A partially executed handler is not rolled back.
  • A committed transaction is not reverted.
  • A queued job is still queued.

For consequential operations, pair client cancellation with server-supported idempotency: a client-generated idempotency key, a unique constraint, or an explicit DELETE/compensating action with its own semantics. Retrying a cancelled POST without one of those is how you get duplicate charges.

Check AbortSignal.any compatibility before adding a fallback

Detect AbortSignal.any and AbortSignal.timeout separately

const hasAny = typeof AbortSignal.any === "function";
const hasTimeout = typeof AbortSignal.timeout === "function";

Support for fetch does not imply support for either. AbortSignal.any is the youngest of the three — it landed in Chromium 116, Firefox 124, Safari 17.4 and Node.js 20.3.0, per MDN's compatibility data at the time of writing. AbortSignal.timeout arrived earlier (Chromium 103, Firefox 100, Safari 16, Node 17.3). Verify against the current compatibility table rather than trusting these numbers as permanent; they drift in both directions as old versions fall out of support.

Check them independently, because a target that has one usually lacks the other only in a narrow window — and you want your fallback to degrade to "timeout only, no composition" rather than "no deadline at all".

What an AbortSignal.any fallback must preserve

If you must support older targets, an anySignal() polyfill has four obligations. Getting three right still leaves a subtle bug:

  1. Already-aborted inputs short-circuit, in iterable order.
  2. The first reason wins by identity, and later aborts leave it alone.
  3. Listeners are removed when the composite settles, or you leak one listener per operation.
  4. Timers are cleared when the request finishes early.

A minimal implementation that honours all four:

any-signal-fallback.js
export function anySignal(signals) {
const list = [...signals];
for (const signal of list) {
  if (!(signal instanceof AbortSignal)) {
    throw new TypeError("Expected an AbortSignal");
  }
}

const controller = new AbortController();
if (list.length === 0) return controller.signal; // never aborts

// 1. Already-aborted input wins immediately, in iteration order.
for (const signal of list) {
  if (signal.aborted) {
    controller.abort(signal.reason);
    return controller.signal;
  }
}

const cleanups = [];
const cleanupAll = () => cleanups.splice(0).forEach((fn) => fn());

for (const signal of list) {
  const onAbort = () => {
    // 2. The source's reason is forwarded as-is; later aborts are no-ops.
    controller.abort(signal.reason);
    cleanupAll(); // 3. remove every listener once we have settled
  };
  signal.addEventListener("abort", onAbort, { once: true });
  cleanups.push(() => signal.removeEventListener("abort", onAbort));
}

// 4. Timer cleanup is the caller's job, because the caller owns the timer.
return controller.signal;
}

The timer obligation has to live with the caller, since the polyfill does not know how the timeout signal was produced:

const timeout = new AbortController();
const timer = setTimeout(
  () => timeout.abort(new DOMException("timed out", "TimeoutError")),
  5000
);

try {
  const signal = anySignal([userController.signal, timeout.signal]);
  // ...use signal
} finally {
  clearTimeout(timer); // required: otherwise the timer outlives the request
}

Two honest disclosures about this fallback. It depends on signal.reason, which older engines do not implement — there, signal.reason is undefined, so the fallback cannot forward the original reason and ends up with the platform's default abort reason instead. And a setTimeout deadline is a wall-clock timer, not the active-time behaviour described above. It is a compatibility shim, not an exact replacement. If you are writing new code and your targets support AbortSignal.any, skip the shim entirely.

Conclusion: make cancellation ownership and timeout scope explicit

The reason Promise.race keeps coming back is that it feels like a one-liner. It is really a deferred bug: a request nobody owns, a body nobody bounds, and a failure nobody can identify.

AbortSignal.any replaces it with three explicit decisions:

  • Who can cancel. A fresh AbortController per operation, aborted with a reason the app defines.
  • How long it may take. AbortSignal.timeout(ms), understood as a timer that fires, not a wall-clock contract.
  • What is covered. The composed signal wraps fetch and the body read, and stops there.

Checklist for the implementation:

  1. Fresh AbortController per operation; cancel the previous one with its own controller before starting the replacement.
  2. Exactly one composed signal per operation: AbortSignal.any([controller.signal, AbortSignal.timeout(ms)]).
  3. Check response.ok explicitly — 4xx and 5xx are not fetch rejections.
  4. Branch on the caught value first (instanceof, then name); use signal.reason only to explain which cancellation won.
  5. Guard every UI write with an operation identity token, and restore state in finally.
  6. Test both cancellation points: before headers, and after headers while the body is still streaming. The second is the case that catches a Promise.race implementation.
  7. Treat client abort as a client-side event. Add server-side idempotency before retrying anything consequential.

Further Reading

Primary sources

Share this post

More posts

Loading comments…