More JavaScript answers

by Danny
Published 2 min read

Use AbortController to cancel a fetch, AbortSignal.timeout to give up after a set time, and AbortSignal.any to combine both. Here is how each one works.

The short answer

#

fetch has no timeout option, but it accepts a signal. Pass AbortSignal.timeout(ms) to give up after a set time, or create an AbortController and call abort() to cancel on demand. When the signal fires, the fetch promise rejects with a DOMException you can check by name.


_12
try {
_12
const response = await fetch('/api/report', {
_12
signal: AbortSignal.timeout(5000),
_12
});
_12
const data = await response.json();
_12
} catch (error) {
_12
if (error.name === 'TimeoutError') {
_12
console.warn('The request took longer than 5 seconds');
_12
} else {
_12
throw error;
_12
}
_12
}

Why it happens

#

A promise on its own cannot be cancelled. The platform solves this with abort signals: an AbortSignal is an object that can switch once from "not aborted" to "aborted", and APIs that accept one stop their work when that happens. fetch closes the request, and the promise rejects.

The name of the error tells you why it stopped:

  • AbortError when you called controller.abort().
  • TimeoutError when a signal from AbortSignal.timeout() expired.

The same signals work with other APIs too, including addEventListener, streams, and many Node.js functions.

How to fix it

#

Cancel on demand with AbortController

Create a controller, pass its signal to fetch, and call abort() when the result is no longer needed, such as when the user starts a new search.


_15
let controller;
_15
_15
async function search(query) {
_15
controller?.abort();
_15
controller = new AbortController();
_15
_15
try {
_15
const response = await fetch(`/api/search?q=${encodeURIComponent(query)}`, {
_15
signal: controller.signal,
_15
});
_15
renderResults(await response.json());
_15
} catch (error) {
_15
if (error.name !== 'AbortError') throw error;
_15
}
_15
}

This stops stale responses from an earlier search overwriting newer results.

Add a timeout with AbortSignal.timeout

AbortSignal.timeout(ms) returns a signal that aborts itself after the given number of milliseconds. You do not need to create a controller or clear a timer.


_10
const response = await fetch(url, { signal: AbortSignal.timeout(8000) });

Combine a timeout and manual cancel with AbortSignal.any

AbortSignal.any() takes a list of signals and returns one that aborts when any of them does. Its reason comes from the signal that fired first.


_10
const controller = new AbortController();
_10
cancelButton.addEventListener('click', () => controller.abort());
_10
_10
const signal = AbortSignal.any([
_10
controller.signal,
_10
AbortSignal.timeout(10000),
_10
]);
_10
_10
const response = await fetch('/api/export', { signal });

AbortSignal.timeout and AbortSignal.any are both supported in all current major browsers and in current Node.js LTS releases. AbortSignal.any became Baseline in 2024, so check your support targets if you need older browsers.

Cancel inside your own async functions

Pass the signal through so callers can stop your code as well as the request.


_10
async function loadAll(urls, { signal } = {}) {
_10
const results = [];
_10
for (const url of urls) {
_10
signal?.throwIfAborted();
_10
const response = await fetch(url, { signal });
_10
results.push(await response.json());
_10
}
_10
return results;
_10
}

Common pitfalls

#
  • Reusing a controller after abort(). A signal stays aborted for good, so create a new controller for each request.
  • Treating every abort as a failure. Check error.name and ignore AbortError when you cancelled on purpose.
  • Building a timeout with Promise.race. The request carries on running in the background; a signal actually stops it.
  • Forgetting that the timeout covers the body too. If the signal fires while you are reading response.json(), that call rejects.
  • Aborting in a React effect cleanup and showing an error message. That abort is expected; skip the error state for it.
#

Was this resource helpful?