Skip to content
Tutorials Center
My learning

Topics

Lesson 76 of 156 ยท Asynchronous JavaScript

Cancelling with AbortController

Cancel fetch requests and other async work with AbortController, add timeouts with AbortSignal.timeout(), and remove event listeners with one call.

Starting asynchronous work is easy. Stopping it is the part people forget. A user types in a search box and every keystroke starts a request, but only the last answer matters. Someone opens a page, gets bored and navigates away while a big download is still running. A server hangs and your spinner keeps spinning forever.

Promises can't be cancelled on their own. Instead, the web platform has one shared cancellation tool: AbortController and the AbortSignal it produces. fetch() understands it, addEventListener() understands it, many Node.js APIs understand it, and you can teach your own functions to understand it too. This lesson shows how.

As in the fetch lesson, the sandbox here has no server. The demos use data: URLs and simulated slow requests that react to a signal exactly the way a real fetch() does.

Controller and signal

The idea has two halves:

  • An AbortController is the remote control. Whoever holds it can call controller.abort().
  • Its AbortSignal (controller.signal) is the receiver. You pass the signal to the work you might want to cancel. The work watches it and stops when it fires.

Splitting them is deliberate: you can hand the signal to many functions without giving them the power to cancel anything themselves.

JS The basics of AbortController

Press Run (or Ctrl + Enter) to see the console output here.

No output.

A signal can only go from "not aborted" to "aborted", once. After that, signal.aborted stays true, and signal.reason holds why. If you call abort() with no argument, the reason is a DOMException named "AbortError". You can also pass your own reason, such as controller.abort(new Error("User left the page")).

Aborting a fetch

Pass the signal in the options of fetch(). If you abort before the response has fully arrived, the request is cancelled and the promise rejects with the signal's reason, normally an AbortError. If you abort while the body is still being read, response.json() rejects instead.

JavaScript
const controller = new AbortController();

const promise = fetch("https://api.example.com/big-report", {
  signal: controller.signal,
});

// Later, maybe when the user clicks "Cancel":
controller.abort();

try {
  const response = await promise;
} catch (error) {
  if (error.name === "AbortError") {
    console.log("Request cancelled.");
  } else {
    throw error; // a real failure: let it surface
  }
}

Checking error.name matters. A cancellation is usually something you asked for, so it shouldn't show an error message to the user. Real failures should.

Here is a real fetch() cancelled straight after it starts. The URL is a data: URL, so no server is involved, but the cancellation follows the same path as a network request:

JS Cancel a real fetch() call

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Making your own functions abortable

Any async function can support cancellation by accepting a signal, the same way fetch() does. The pattern is:

  1. If the signal is already aborted, fail right away. signal.throwIfAborted() does this in one line.
  2. Listen for the abort event, stop the work and reject with signal.reason.
  3. Clean up the listener when the work finishes normally.
JS An abortable delay

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The loop gets through two steps before the controller fires. Because delay() clears its timer, the cancelled step truly stops instead of just being ignored, which is the whole point.

signal.throwIfAborted() and abort reasons are supported in all current browsers and Node.js 17.3 and later.

Search as you type: cancel the previous request

The most common real use is a search box. Each keystroke starts a new request, so an old, slow answer could arrive after a newer one and overwrite the correct results. Cancelling the previous request fixes both the wasted work and that race condition.

Cancelling stale search requests

Type quickly and the console shows most searches being cancelled; only the latest one updates the list. In a real app you'd often combine this with a short debounce (see timers) so you don't even start a request on every keystroke.

Timeouts with AbortSignal.timeout()

For a timeout you don't need your own controller. AbortSignal.timeout(ms) returns a signal that aborts itself after the given time, with a reason named "TimeoutError" rather than "AbortError". That lets you tell "too slow" apart from "cancelled by the user":

JavaScript
try {
  const response = await fetch("https://api.example.com/slow", {
    signal: AbortSignal.timeout(5000), // give up after 5 seconds
  });
  const data = await response.json();
} catch (error) {
  if (error.name === "TimeoutError") {
    showMessage("The server is taking too long. Please try again.");
  } else if (error.name === "AbortError") {
    // cancelled on purpose: stay quiet
  } else {
    showMessage("Network problem.");
  }
}

Unlike the Promise.race() timeout from the combinators lesson, this version really cancels the request, so the browser stops downloading.

Combining signals with AbortSignal.any()

Sometimes you want both: a timeout and a Cancel button. AbortSignal.any([signalA, signalB]) creates a signal that aborts as soon as any of the given signals does, and takes over that signal's reason.

JS Timeout or cancel, whichever comes first

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Support. AbortSignal.timeout() works in all current browsers and Node.js 17.3+. AbortSignal.any() is newer: it became available in every major browser during 2024 (and in Node.js 20.3). For older browsers, wire a controller up by hand: listen for abort on each source signal and call controller.abort(signal.reason).

Removing event listeners with a signal

addEventListener() also accepts a signal option. When the signal aborts, the listener is removed automatically. With one controller you can remove a whole group of listeners in a single call, without keeping references to each handler function:

JavaScript
const controller = new AbortController();
const { signal } = controller;

window.addEventListener("resize", onResize, { signal });
window.addEventListener("keydown", onKey, { signal });
document.addEventListener("pointermove", onMove, { signal });

// Later, when the widget is closed:
controller.abort(); // all three listeners are gone

This is a tidy way to clean up components, dialogs and drag-and-drop interactions. You'll use event listeners a lot in the Events lesson.

Good habits

  • Create a new controller for each operation. Once aborted, a controller stays aborted forever, so it can't be reused.
  • Treat AbortError as normal. Don't show it as a failure, but do let other errors through.
  • Really stop the work. An abortable function should clear its timers, close connections and remove its listeners, not just reject.
  • Cancel on teardown. When a component, page section or modal goes away, abort what it started.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which object do you pass to fetch() to make it cancellable?

    fetch() takes { signal: controller.signal }. The controller stays with whoever is allowed to cancel.
  2. 2. A request is cancelled with controller.abort(). What is the rejection's name?

    Calling abort() without a reason rejects with a DOMException named AbortError. AbortSignal.timeout() uses TimeoutError instead.
  3. 3. Why cancel the previous request in a search-as-you-type box?

    Responses can arrive out of order. Aborting stale requests means only the latest query can update the page.
  4. 4. What does AbortSignal.any([a, b]) return?

    any() follows whichever source signal aborts first and copies its reason.
  5. 5. Can you reuse an AbortController after calling abort()?

    A signal aborts once and for all. Make a fresh controller for each new operation.

Summary

  • AbortController cancels; its signal is passed to the work that should listen.
  • fetch(url, { signal }) rejects with an AbortError when aborted; check error.name to tell cancellations from real failures.
  • Your own async functions can accept a signal: call throwIfAborted(), listen for abort, stop the work and reject with signal.reason.
  • AbortSignal.timeout(ms) aborts with a TimeoutError; AbortSignal.any() combines signals.
  • addEventListener(type, fn, { signal }) removes listeners when the signal aborts.

Next: Modules: import and export โ€” split your code into files that share exactly what they choose to.