Trivia Questions1 min readPremium

AbortController in JavaScript

An AbortController gives you a signal you can pass to an async operation and an abort() method that cancels it. It’s the standard way to cancel a fetch, and the same signal works with event listeners, streams and your own functions.

const controller = new AbortController();

fetch('/api/search?q=react', { signal: controller.signal })
  .then((res) => res.json())
  .then(render)
  .catch((err) => {
    if (err.name === 'AbortError') return; // cancelled on purpose
    showError(err);
  });

controller.abort(); // the fetch promise rejects with an AbortError

1. Why it matters: race conditions

In a search box, the response for “re” can arrive after the response for “react”. Cancel the previous request whenever a new one starts:

let controller;

async function search(query) {
  controller?.abort();
  controller = new AbortController();

  try {
    const res = await fetch(`/api/search?q=${encodeURIComponent(query)}`, {
      signal: controller.signal,
    });
    render(await res.json());
  } catch (err) {
    if (err.name !== 'AbortError') showError(err);
  }
}

2. In a React effect

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

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

  return () => controller.abort(); // runs when id changes or on unmount
}, [id]);

The cleanup cancels the stale request, so an old response can never overwrite newer state.

3. Timeouts

const res = await fetch(url, { signal: AbortSignal.timeout(5000) });

A timeout rejects with a TimeoutError, not an AbortError, so you can tell “too slow” from “cancelled by the user”.

4. Combining signals

Cancel on whichever comes first, the user or the clock:

const controller = new AbortController();
const signal = AbortSignal.any([controller.signal, AbortSignal.timeout(5000)]);

fetch(url, { signal });
cancelButton.onclick = () => controller.abort();

5. One signal, many operations

A single abort() cancels everything that shares the signal, including event listeners:

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

window.addEventListener('resize', onResize, { signal });
window.addEventListener('scroll', onScroll, { signal });
fetch('/api/feed', { signal });

controller.abort(); // removes both listeners and cancels the request

This is a neat way to tear down a widget without tracking every removeEventListener.

6. Making your own function abortable

function delay(ms, { signal } = {}) {
  return new Promise((resolve, reject) => {
    if (signal?.aborted) return reject(signal.reason);

    const id = setTimeout(resolve, ms);

    signal?.addEventListener(
      'abort',
      () => {
        clearTimeout(id);
        reject(signal.reason);
      },
      { once: true }
    );
  });
}

Three things to get right: check signal.aborted first, clean up your resource on abort, and reject with signal.reason. Practise it: abortable delay.

7. Limits

  • A controller is single-use. Once aborted, its signal stays aborted. Create a new one per operation.
  • The server may already have done the work. Aborting stops the browser waiting; it doesn’t undo a POST that reached the server.
  • Aborting after completion does nothing.

Quick reference

Task API
Cancel manually new AbortController(), then controller.abort()
Cancel after a time AbortSignal.timeout(ms)
Cancel on any of several signals AbortSignal.any([a, b])
Check state signal.aborted, signal.reason
React to cancellation signal.addEventListener('abort', fn) or signal.throwIfAborted()

Follow-up questions to expect

  • “How do you tell a cancellation from a real error?” Check err.name: 'AbortError' or 'TimeoutError'.
  • “Does Promise.race cancel the losers?” No. Pass each a signal and abort it. See Promise.all vs race.
  • “How would you cancel a debounced search?” Clear the timer and abort the in-flight request. Try it in autocomplete search.