Canceling and Timeouts

Updated · 8 min read
hardES2026javascriptabortcontrollerfetchtimeoutscancellation

Promises have no built-in way to cancel the work behind them. When a user types a new search term, leaves a page, or clicks Cancel, the old requests keep running and their results arrive late, sometimes overwriting newer data. AbortController solves this: it creates an AbortSignal that you pass to fetch, event listeners, timers and your own functions; calling controller.abort() tells all of them to stop. AbortSignal.timeout(ms) and AbortSignal.any([...]) build timeouts and combined signals in one line.

In One Minute

  • const controller = new AbortController() gives you controller.signal and controller.abort(reason?).
  • Pass the signal to fetch(url, { signal }); aborting rejects the fetch with an AbortError.
  • AbortSignal.timeout(ms) aborts automatically after ms, with a TimeoutError.
  • AbortSignal.any([signalA, signalB]) aborts when either does: a user Cancel or a timeout.
  • Make your own functions cancelable by checking signal.aborted, calling signal.throwIfAborted(), or listening for the abort event.

AbortController and AbortSignal

MemberDescription
new AbortController()It is used to create a controller that owns one signal.
controller.signalThe AbortSignal to pass to operations.
controller.abort(reason?)It is used to abort; the reason defaults to a DOMException named AbortError.
signal.abortedtrue once aborted.
signal.reasonWhy it was aborted.
signal.throwIfAborted()It is used to throw signal.reason if already aborted.
signal.addEventListener("abort", fn)It is used to run code when it aborts.
AbortSignal.timeout(ms)A signal that aborts after ms with a TimeoutError.
AbortSignal.any(signals)A signal that aborts when any of the given signals abort.
AbortSignal.abort(reason?)An already-aborted signal.
basics.js▶ Try it
const controller = new AbortController();
const { signal } = controller;
 
signal.addEventListener("abort", () => console.log("abort event, reason:", signal.reason.name));
console.log(signal.aborted);
 
controller.abort();
console.log(signal.aborted, signal.reason.name);
 
controller.abort();
try {
  signal.throwIfAborted();
} catch (err) {
  console.log("throwIfAborted threw", err.name);
}
Output
false
abort event, reason: AbortError
true AbortError
throwIfAborted threw AbortError

A signal aborts once; calling abort() again does nothing. One signal can be shared by many operations, so one call cancels them all.

Canceling fetch

api/report.json
{ "total": 655 }
cancel-fetch.html
<button id="cancel">Cancel</button>
<script type="module">
  const controller = new AbortController();
  document.querySelector("#cancel").addEventListener("click", () => controller.abort());

  try {
    const res = await fetch("/api/report.json", { signal: controller.signal });
    console.log("loaded", (await res.json()).total);
  } catch (err) {
    if (err.name === "AbortError") console.log("Report request canceled");
    else console.log("Failed:", err.message);
  }
</script>
Output
Report request canceled

Explanation: the slow report request was still in progress when the checker clicked Cancel. controller.abort() stopped the network request and rejected the fetch promise with an AbortError. Check err.name to tell a deliberate cancellation (usually not an error worth showing) from a real failure.

Timeouts with AbortSignal.timeout

AbortSignal.timeout(ms) creates a signal that aborts by itself, with a reason named TimeoutError:

timeout.html
<script type="module">
  try {
    await fetch("/api/report.json", { signal: AbortSignal.timeout(200) });
  } catch (err) {
    console.log(err.name, "|", err.message);
  }
</script>
Output
TimeoutError | signal timed out

Unlike Promise.race with a timer, this actually stops the request, freeing the connection.

Combining Signals with AbortSignal.any

Real interfaces need several reasons to stop: the user clicks Cancel, or a timeout passes, or the component closes. AbortSignal.any combines them into one signal:

any.html
<button id="cancel">Cancel</button>
<script type="module">
  const userCancel = new AbortController();
  document.querySelector("#cancel").addEventListener("click", () => userCancel.abort());

  const signal = AbortSignal.any([userCancel.signal, AbortSignal.timeout(250)]);
  try {
    await fetch("/api/report.json", { signal });
  } catch (err) {
    const why = err.name === "TimeoutError" ? "took too long" : err.name === "AbortError" ? "canceled by the user" : err.message;
    console.log(`Stopped: ${why}`);
  }
</script>
Output
Stopped: took too long

Nobody clicked Cancel, so the timeout fired first, and the combined signal's reason is the timeout's TimeoutError.

Making Your Own Functions Cancelable

Any async function can accept a signal. Check it between steps, and pass it on to anything that supports it:

cancelable.js▶ Try it
function sleep(ms, { signal } = {}) {
  return new Promise((resolve, reject) => {
    signal?.throwIfAborted();
    const timer = setTimeout(resolve, ms);
    signal?.addEventListener("abort", () => {
      clearTimeout(timer);
      reject(signal.reason);
    }, { once: true });
  });
}
 
async function processPayments(ids, { signal } = {}) {
  const done = [];
  for (const id of ids) {
    signal?.throwIfAborted();
    await sleep(10, { signal });
    done.push(id);
  }
  return done;
}
 
const controller = new AbortController();
setTimeout(() => controller.abort(), 35);
 
try {
  await processPayments([1, 2, 3, 4, 5, 6], { signal: controller.signal });
} catch (err) {
  console.log("stopped:", err.name);
}
 
console.log(await processPayments([1, 2], {}));
Output
stopped: AbortError
[1, 2]

Explanation: sleep rejects as soon as the signal aborts, clearing its timer so nothing is left running. processPayments checks the signal before each item and passes it on to sleep, so the abort after 35 ms stops the loop partway through. Making the signal optional ({ signal } = {} and signal?.) keeps the function easy to call when cancellation isn't needed.

Other APIs That Accept a Signal

APIEffect of aborting
fetch(url, { signal })Cancels the request; rejects with the signal's reason
addEventListener(type, fn, { signal })Removes the listener
Node.js node:timers/promises (setTimeout(ms, value, { signal }))Cancels the timer
Node.js fs.readFile(path, { signal }), child_process, stream.pipelineCancels the operation
ReadableStream piping (pipeTo(dest, { signal }))Stops the pipe

Avoiding Stale Results

The most common real bug cancellation fixes: a user types quickly, several searches run, and a slow, older response arrives after a newer one, showing results for the wrong text. Abort the previous request whenever a new one starts:

latest-only.js▶ Try it
const fakeSearch = (term, { signal }) =>
  new Promise((resolve, reject) => {
    const timer = setTimeout(() => resolve(`results for "${term}"`), term.length === 1 ? 50 : 10);
    signal.addEventListener("abort", () => { clearTimeout(timer); reject(signal.reason); }, { once: true });
  });
 
let current;
async function search(term) {
  current?.abort();
  current = new AbortController();
  try {
    console.log(await fakeSearch(term, { signal: current.signal }));
  } catch (err) {
    if (err.name !== "AbortError") throw err;
    console.log(`(search for "${term}" canceled)`);
  }
}
 
await Promise.all([search("N"), search("Na"), search("Nav")]);
Output
(search for "N" canceled)
(search for "Na" canceled)
results for "Nav"

Without the abort, the slow search for "N" would have finished last and overwritten the correct results for "Nav".

In Practice

The Fee Tracker's report panel combines everything: one controller for the panel's lifetime (closing the panel cancels all its work, including listeners), plus a timeout per request:

api/totals.json
{ "byGrade": { "9": 165, "11": 85, "12": 300 } }
panel.html
<div id="panel"><p id="status">Loading...</p><button id="close">Close</button></div>
<script type="module">
  const panel = new AbortController();
  const status = document.querySelector("#status");

  document.querySelector("#close").addEventListener("click", () => {
    panel.abort(new DOMException("Panel closed", "AbortError"));
    console.log("panel closed, aborted:", panel.signal.aborted);
  }, { signal: panel.signal });

  async function loadTotals() {
    const signal = AbortSignal.any([panel.signal, AbortSignal.timeout(2000)]);
    const res = await fetch("/api/totals.json", { signal });
    return res.json();
  }

  try {
    const { byGrade } = await loadTotals();
    status.textContent = Object.entries(byGrade).map(([g, t]) => `Grade ${g}: $${t}`).join(", ");
    console.log(status.textContent);
  } catch (err) {
    if (err.name !== "AbortError") status.textContent = "Couldn't load totals";
  }
</script>
Output
Grade 9: $165, Grade 11: $85, Grade 12: $300
panel closed, aborted: true

The close listener itself was registered with the panel's signal, so aborting also removes it: a second click would do nothing.

Common Mistakes

Treating AbortError as a failure. It's usually expected; don't show an error message for it.

Reusing an aborted controller. A signal aborts once. Create a new AbortController for each new operation.

Using Promise.race for timeouts on fetch. The request keeps running. Use AbortSignal.timeout.

Not passing the signal down. Inner calls keep running after the outer one is canceled. Pass { signal } through every layer.

Practice

Challenge: Write fetchJsonWithTimeout(url, ms, signal) that combines an optional caller signal with a timeout and returns parsed JSON, then call it on the served /api/totals.json.

Show solution
combined.html
<script type="module">
  async function fetchJsonWithTimeout(url, ms, signal) {
    const signals = [AbortSignal.timeout(ms), ...(signal ? [signal] : [])];
    const res = await fetch(url, { signal: AbortSignal.any(signals) });
    if (!res.ok) throw new Error(`HTTP ${res.status}`);
    return res.json();
  }
  const data = await fetchJsonWithTimeout("/api/totals.json", 1000);
  console.log(Object.keys(data.byGrade).length, "grades");
</script>
Output
3 grades

Quick check: Canceling and timeouts

3 questions
1What does controller.abort() do to a fetch that received controller.signal?
2What does AbortSignal.timeout(500) create?
3How do you abort when either the user cancels or a timeout passes?

Key Takeaways

TaskCode
Createconst c = new AbortController()
Cancel a requestfetch(url, { signal: c.signal }); c.abort()
Timeout{ signal: AbortSignal.timeout(5000) }
Either reasonAbortSignal.any([c.signal, AbortSignal.timeout(5000)])
Check inside a loopsignal.throwIfAborted()
Recognize cancellationerr.name === "AbortError"

Was this tutorial helpful?

Lesson 106 of 139