Most async bugs are not about starting work. They are about work that keeps going after nobody wants it. A search box fires a request for every keystroke and an old response arrives last, overwriting the right results. A component unmounts but its fetch still resolves and updates state. A slow API call hangs for a minute because nothing told it to give up.

JavaScript has a standard answer to all of these: AbortController and AbortSignal. They work with fetch, with event listeners, with many Node.js APIs and with any function you write yourself. This article is for developers who have seen AbortController in a snippet and want to use it with confidence. We will cover the basics, timeouts, combining signals, making your own code cancellable and the mistakes to avoid.

The two pieces

#

The controller is the part that cancels. The signal is the part you hand to the work being cancelled.


_13
const controller = new AbortController();
_13
const { signal } = controller;
_13
_13
fetch("/api/articles", { signal })
_13
.then((res) => res.json())
_13
.then((articles) => render(articles))
_13
.catch((err) => {
_13
if (err.name === "AbortError") return; // we cancelled it, not a failure
_13
showError(err);
_13
});
_13
_13
// later
_13
controller.abort();

When you call abort(), the signal's aborted property becomes true, it fires an abort event, and fetch rejects. By default the rejection is a DOMException with the name AbortError.

Splitting the two roles is deliberate. You can pass a signal to code you do not trust with the power to cancel, and only the owner of the controller can actually abort.

Giving a reason

#

abort() accepts an optional reason. It is stored on signal.reason, and fetch rejects with that value instead of the default error.


_10
controller.abort(new Error("User navigated away"));
_10
_10
signal.reason; // Error: User navigated away

A reason makes logs far more useful than a bare "The operation was aborted". If you pass a reason, check for it in your error handling rather than relying only on the AbortError name.

Timeouts with AbortSignal.timeout

#

The most common reason to cancel is that something took too long. AbortSignal.timeout() creates a signal that aborts itself after a number of milliseconds.


_11
try {
_11
const res = await fetch("/api/report", { signal: AbortSignal.timeout(5000) });
_11
const report = await res.json();
_11
render(report);
_11
} catch (err) {
_11
if (err.name === "TimeoutError") {
_11
showMessage("The report is taking too long. Please try again.");
_11
} else {
_11
throw err;
_11
}
_11
}

A timeout signal rejects with a DOMException named TimeoutError, not AbortError. That makes it easy to tell "too slow" apart from "cancelled on purpose", and to show the user a different message.

This replaces the older pattern of creating a controller and calling setTimeout(() => controller.abort(), 5000) by hand, along with the cleanup you had to remember to do.

Combining signals with AbortSignal.any

#

Real work often has more than one reason to stop. A request should end if the user cancels it or if it takes too long. AbortSignal.any() takes an array of signals and returns one that aborts as soon as any of them does.


_10
const controller = new AbortController();
_10
cancelButton.addEventListener("click", () => controller.abort(), { once: true });
_10
_10
const signal = AbortSignal.any([
_10
controller.signal,
_10
AbortSignal.timeout(10_000),
_10
]);
_10
_10
const res = await fetch("/api/export", { signal });

The combined signal's reason is the reason from whichever signal fired first, so your error handling still knows whether it was a timeout or a user action.

Cancelling event listeners

#

addEventListener accepts a signal option. When the signal aborts, the listener is removed. This is often neater than keeping references to handler functions so you can call removeEventListener later.


_14
function enableDragging(element) {
_14
const controller = new AbortController();
_14
const { signal } = controller;
_14
_14
element.addEventListener("pointerdown", onDown, { signal });
_14
window.addEventListener("pointermove", onMove, { signal });
_14
window.addEventListener("pointerup", onUp, { signal });
_14
_14
return () => controller.abort(); // removes all three at once
_14
}
_14
_14
const disableDragging = enableDragging(card);
_14
// later
_14
disableDragging();

One controller can own as many listeners as you like, which makes teardown a single call.

Making your own functions cancellable

#

Any function that does async work can accept a signal. There are three tools for this:

  • signal.aborted tells you whether it has already been aborted.
  • signal.throwIfAborted() throws signal.reason if it has been aborted, and does nothing otherwise.
  • The abort event lets you react the moment it happens.

Here is a cancellable delay, which shows all three:


_17
function delay(ms, { signal } = {}) {
_17
return new Promise((resolve, reject) => {
_17
signal?.throwIfAborted();
_17
_17
const timer = setTimeout(() => {
_17
signal?.removeEventListener("abort", onAbort);
_17
resolve();
_17
}, ms);
_17
_17
function onAbort() {
_17
clearTimeout(timer);
_17
reject(signal.reason);
_17
}
_17
_17
signal?.addEventListener("abort", onAbort, { once: true });
_17
});
_17
}

Two details matter. First, check the signal before starting, because it may already be aborted. Second, remove the abort listener when the work finishes normally. Otherwise long-lived signals collect listeners from every completed task.

For longer functions made of several steps, check between steps and pass the signal down:


_10
async function syncArticles({ signal }) {
_10
const res = await fetch("/api/articles", { signal });
_10
const articles = await res.json();
_10
_10
for (const article of articles) {
_10
signal.throwIfAborted();
_10
await saveLocally(article, { signal });
_10
}
_10
}

A search box that never shows stale results

#

Here is the race condition from the introduction, fixed. Each new search aborts the previous one, so an old response can never overwrite a newer one.


_15
let current;
_15
_15
searchInput.addEventListener("input", async (event) => {
_15
current?.abort();
_15
current = new AbortController();
_15
const { signal } = current;
_15
_15
try {
_15
const query = encodeURIComponent(event.target.value);
_15
const res = await fetch(`/api/search?q=${query}`, { signal });
_15
renderResults(await res.json());
_15
} catch (err) {
_15
if (err.name !== "AbortError") showError(err);
_15
}
_15
});

The same idea works in React. Create a controller inside useEffect, pass its signal to the request, and abort it in the cleanup function.


_12
useEffect(() => {
_12
const controller = new AbortController();
_12
_12
fetch(`/api/users/${userId}`, { signal: controller.signal })
_12
.then((res) => res.json())
_12
.then(setUser)
_12
.catch((err) => {
_12
if (err.name !== "AbortError") setError(err);
_12
});
_12
_12
return () => controller.abort();
_12
}, [userId]);

When userId changes or the component unmounts, React runs the cleanup and the stale request is cancelled. This also behaves correctly under Strict Mode in development, where effects run, clean up and run again.

In Node.js

#

Node supports signals across much of its standard library, not just fetch.


_10
import { setTimeout as sleep } from "node:timers/promises";
_10
import { readFile } from "node:fs/promises";
_10
_10
const signal = AbortSignal.timeout(2000);
_10
_10
await sleep(500, undefined, { signal });
_10
const data = await readFile("./large.json", { encoding: "utf8", signal });

The promise-based timers, fs/promises functions such as readFile, child_process functions such as spawn, and events.once all accept a signal option. A common server pattern is to abort work for a request when the client disconnects, by aborting a controller from the request's close event.

Common mistakes

#
  • Reusing a controller. Once aborted, a controller stays aborted. Create a new one for each new piece of work.
  • Treating an abort as a failure. Showing an error message because the user navigated away is confusing. Check err.name or signal.aborted before reporting.
  • Forgetting the body. Aborting also cancels reading the response body, so res.json() can reject with the abort error too. Keep it inside the same try.
  • Expecting the server to stop. Aborting a fetch stops the client waiting. The server may still finish the request, so do not rely on abort to undo a write.
  • Leaking listeners on long-lived signals. If your function adds an abort listener, remove it when the work completes.

Browser support

#

AbortController, AbortSignal and fetch support for signals have been available in every major browser for years and are Baseline widely available. signal.throwIfAborted() and AbortSignal.timeout() are supported in all current major browsers. AbortSignal.any() is the newest piece: it arrived in Chrome and Edge 116, Firefox 124 and Safari 17.4, and has been Baseline since March 2024.

In Node.js, all of these are available in every supported release, which in late 2026 means Node 22, 24 and 26.

When not to use it

#
  • Work that must finish once started. If stopping halfway would leave data inconsistent, do not offer cancellation, or make the operation safe to retry instead.
  • CPU-heavy synchronous code. A signal cannot interrupt a tight loop. The loop has to check the signal itself, or the work should move to a web worker that you can terminate.
  • A single short request that nobody waits on. Not every fetch needs a controller. Add one when there is a real reason to stop: a timeout, a user action, a newer request or a component going away.

Wrapping up

#
  • AbortController cancels, AbortSignal is what you pass to the work. Only the controller's owner can abort.
  • Use AbortSignal.timeout() for deadlines and check for TimeoutError to tell it apart from a deliberate AbortError.
  • AbortSignal.any() combines user cancellation, timeouts and other reasons into one signal.
  • Pass a signal to addEventListener to remove many listeners with one call.
  • Make your own async functions accept a signal: check it first, listen for abort, and clean up your listener when you finish.
file under:
Javascript

Was this article helpful?

About the author

Danny Engineering

A software engineer with a strong belief in human-centric design and driven by a deep empathy for users. Combining the latest technology with human values to build a better, more connected world.