---
title: "Cancelling async work properly with AbortController and AbortSignal"
description: "Learn to cancel fetch requests, timers, listeners and your own async functions with AbortController, AbortSignal.timeout and AbortSignal.any, in the browser and in Node."
url: https://www.danny.engineering/article/cancelling-async-work-properly-with-abortcontroller-and-abortsignal
author: Danny
published: 2026-11-27T00:00:00.000Z
updated: 2026-11-27T17:23:00.000Z
tags: ["Javascript"]
---

# Cancelling async work properly with AbortController and AbortSignal

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.


```javascript
const controller = new AbortController();
const { signal } = controller;

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

// later
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.


```javascript
controller.abort(new Error("User navigated away"));

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.


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


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.


```javascript
const controller = new AbortController();
cancelButton.addEventListener("click", () => controller.abort(), { once: true });

const signal = AbortSignal.any([
  controller.signal,
  AbortSignal.timeout(10_000),
]);

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.


```javascript
function enableDragging(element) {
  const controller = new AbortController();
  const { signal } = controller;

  element.addEventListener("pointerdown", onDown, { signal });
  window.addEventListener("pointermove", onMove, { signal });
  window.addEventListener("pointerup", onUp, { signal });

  return () => controller.abort(); // removes all three at once
}

const disableDragging = enableDragging(card);
// later
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:


```javascript
function delay(ms, { signal } = {}) {
  return new Promise((resolve, reject) => {
    signal?.throwIfAborted();

    const timer = setTimeout(() => {
      signal?.removeEventListener("abort", onAbort);
      resolve();
    }, ms);

    function onAbort() {
      clearTimeout(timer);
      reject(signal.reason);
    }

    signal?.addEventListener("abort", onAbort, { once: true });
  });
}
```


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:


```javascript
async function syncArticles({ signal }) {
  const res = await fetch("/api/articles", { signal });
  const articles = await res.json();

  for (const article of articles) {
    signal.throwIfAborted();
    await saveLocally(article, { signal });
  }
}
```


## 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.


```javascript
let current;

searchInput.addEventListener("input", async (event) => {
  current?.abort();
  current = new AbortController();
  const { signal } = current;

  try {
    const query = encodeURIComponent(event.target.value);
    const res = await fetch(`/api/search?q=${query}`, { signal });
    renderResults(await res.json());
  } catch (err) {
    if (err.name !== "AbortError") showError(err);
  }
});
```


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


```typescript
useEffect(() => {
  const controller = new AbortController();

  fetch(`/api/users/${userId}`, { signal: controller.signal })
    .then((res) => res.json())
    .then(setUser)
    .catch((err) => {
      if (err.name !== "AbortError") setError(err);
    });

  return () => controller.abort();
}, [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`.


```javascript
import { setTimeout as sleep } from "node:timers/promises";
import { readFile } from "node:fs/promises";

const signal = AbortSignal.timeout(2000);

await sleep(500, undefined, { signal });
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.
