← Back to JavaScript, page 9

javascript-0179 · Hard senior

How do you compose cancellation with AbortSignal.any and AbortSignal.timeout, and how do you clean up correctly?

Create one controller per operation, combine the user's signal with AbortSignal.timeout(ms) using AbortSignal.any, pass the combined signal down, and read signal.reason to tell a timeout from a cancel. Check signal.throwIfAborted() between steps, remove listeners in finally, and make abortable helpers reject with the reason so callers can handle both cases separately.

Full answer

An AbortSignal is a one-way notification. A controller aborts, and any number of listeners react. Composition is the interesting part:

  • AbortSignal.timeout(ms) gives a signal that aborts with a TimeoutError after the delay. controller.abort() without a reason uses an AbortError. You can pass any reason: controller.abort(new Error('user left')).
  • AbortSignal.any([a, b]) returns a signal that aborts when the first input aborts, and carries that input's reason. This is how you combine a caller's signal, a timeout, and a component lifecycle signal without writing glue code. Older runtimes need a small helper with listeners.
  • signal.throwIfAborted() is the simple checkpoint between steps of a long operation. signal.aborted and signal.reason expose the state.
  • A helper such as sleep(ms, { signal }) should reject with signal.reason, not with a new generic error, so callers can tell TimeoutError from a user cancel. It must also check signal.aborted first, because an already aborted signal never fires the event again.
  • Always remove the abort listener when the operation finishes normally ({ once: true } plus removeEventListener in finally). Otherwise a long-lived signal collects listeners and keeps the closures alive.
  • Cancellation is cooperative. Aborting does not stop code that never checks the signal. fetch and many Node.js APIs accept signal, and your own functions need to pass it on.
  • Design for partial work: abort can happen at any await. Keep operations idempotent or rollback in catch and finally.
  • Separate three outcomes in the caller: success, aborted by the user (often not an error to report), and timed out (often retried or reported). Check error === signal.reason or error.name.

Pattern for APIs: accept { signal } options, never create a controller you do not own, and document which reason you reject with.

javascript
function sleep(ms, { signal } = {}) {
  return new Promise((resolve, reject) => {
    if (signal?.aborted) return reject(signal.reason);
    const onAbort = () => {
      clearTimeout(timer);
      reject(signal.reason);
    };
    const timer = setTimeout(() => {
      signal?.removeEventListener('abort', onAbort);
      resolve();
    }, ms);
    signal?.addEventListener('abort', onAbort, { once: true });
  });
}

async function runJob(name, steps, { signal, timeoutMs }) {
  const combined = timeoutMs ? AbortSignal.any([signal, AbortSignal.timeout(timeoutMs)].filter(Boolean)) : signal;
  const done = [];
  try {
    for (let i = 1; i <= steps; i++) {
      combined?.throwIfAborted();
      await sleep(40, { signal: combined });
      done.push(i);
    }
    return `${name}: finished ${done.length} steps`;
  } catch (error) {
    const kind = error.name === 'TimeoutError' ? 'timed out' : error.name === 'AbortError' ? 'cancelled by user' : 'failed';
    return `${name}: ${kind} after ${done.length} steps (${error.name})`;
  }
}

(async () => {
  console.log(await runJob('normal', 2, { timeoutMs: 1000 }));

  console.log(await runJob('timeout', 10, { timeoutMs: 100 }));

  const user = new AbortController();
  setTimeout(() => user.abort(), 100);
  console.log(await runJob('user cancel', 10, { signal: user.signal, timeoutMs: 2000 }));

  const custom = new AbortController();
  custom.abort(new Error('component unmounted'));
  console.log(await runJob('custom reason', 3, { signal: custom.signal }));

  const early = AbortSignal.abort();
  console.log('already aborted signal rejects at once:', await sleep(10, { signal: early }).catch((e) => e.name));

  const first = new AbortController();
  const second = new AbortController();
  const any = AbortSignal.any([first.signal, second.signal]);
  second.abort(new Error('second wins'));
  first.abort(new Error('first is too late'));
  console.log('any keeps the first reason:', any.reason.message);

  const controller = new AbortController();
  let listeners = 0;
  const count = () => listeners++;
  controller.signal.addEventListener('abort', count, { once: true });
  controller.abort();
  controller.abort();
  console.log('abort fires once:', listeners, '| reason name:', controller.signal.reason.name);
})();

Run with Node.js v24.22.1 as js-179.js; two runs gave identical output. Output: normal: finished 2 steps timeout: timed out after 2 steps (TimeoutError) user cancel: cancelled by user after 2 steps (AbortError) custom reason: failed after 0 steps (Error) already aborted signal rejects at once: AbortError any keeps the first reason: second wins abort fires once: 1 | reason name: AbortError

Key points

  • AbortSignal.timeout gives TimeoutError; AbortSignal.any combines signals and keeps the reason of the first one.
  • Helpers should check signal.aborted first and reject with signal.reason.
  • Use throwIfAborted between steps and remove listeners in finally.
  • Cancellation is cooperative; pass the signal to everything inside.
  • Tell success, user abort, and timeout apart in the caller.

Common mistakes

  • Rejecting with a generic error and losing the reason.
  • Forgetting to check signal.aborted before adding the listener.
  • Leaving abort listeners attached to a long-lived signal.
  • Reporting a user cancel as a failure.

Follow-ups

  • How would you build a signal that aborts when a component unmounts?
  • How does fetch react to an aborted signal after the headers arrived?
  • How would you implement AbortSignal.any in an older runtime?

Tips

  • Show the three outcomes: done, cancelled, timed out.
  • Mention listener cleanup and cooperative cancellation.
  • Pass the signal down to every async step.