Sub topic 8
Cancelling Requests and Adding Timeouts
A request you start with fetch() keeps running until the server responds or the network fails. Sometimes you no longer want the result: the user typed another character into a search box, left the page, or the server is taking too long. This chapter shows how to cancel requests with AbortController, how to enforce deadlines with AbortSignal.timeout(), and how to tell a cancellation apart from a real failure.
This chapter assumes you are comfortable with async/await, try/catch, and the response.ok check from the error-handling chapter. All examples run in a modern browser console or in an ES module, and both allow top-level await. Node.js 18 and later also supports them.
The working model: controllers and signals
Cancellation in the Fetch API uses two objects with separate jobs:
- An
AbortControlleris the object you call to cancel. It has one method,abort(), and one property,signal. - An
AbortSignalis the read-only side. You pass it tofetch()and other APIs, and they watch it for an abort.
You split them so that the code that decides to cancel holds the controller, and the code that does the work only receives the signal. The work can react to cancellation, but it cannot cancel anything itself.
const controller = new AbortController();
const pending = fetch('https://api.example.com/search?q=fetch', {
signal: controller.signal
});
pending
.then((response) => console.log('Status:', response.status))
.catch((err) => console.log(err.name)); // 'AbortError'
controller.abort();When you call abort(), three things happen:
controller.signal.abortedbecomestrue.- The signal fires an
abortevent. - Every
fetch()using that signal stops its network activity and rejects its promise.
The rejection value is a DOMException whose name is 'AbortError'. Check err.name, not instanceof Error. DOMException is not a subclass of Error in every environment.
A signal is single-use
Once a signal is aborted, it stays aborted. If you pass an already-aborted signal to fetch(), the call rejects right away without sending anything. You cannot reset a controller. Create a new AbortController for each request, or for each group of requests you want to cancel together.
const controller = new AbortController();
controller.abort();
try {
await fetch('https://api.example.com/users', { signal: controller.signal });
} catch (err) {
console.log(err.name); // 'AbortError', and no request was sent
}One signal can cancel many requests
Several requests can share one signal. One abort() call then cancels all of them. This is useful when a page loads several resources and the user navigates away.
const controller = new AbortController();
const { signal } = controller;
const loads = Promise.all([
fetch('https://api.example.com/users', { signal }),
fetch('https://api.example.com/posts', { signal })
]);
controller.abort(); // both fetches reject with AbortError
loads.catch((err) => console.log('Page load cancelled:', err.name));Cancellation covers the body, too
The signal does not stop applying when the headers arrive. It also covers reading the body. If you abort while response.json(), response.text(), or a stream reader is still receiving data, that read rejects with the same abort error.
This matters in your code. In a try block, write return await response.json(), not return response.json(). Without the await, the promise from json() leaves the function before it settles. The catch block never sees an abort that happens during the download.
async function loadReport(signal) {
try {
const response = await fetch('https://api.example.com/report', { signal });
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return await response.json(); // await keeps body errors inside this try
} catch (err) {
if (err.name === 'AbortError') {
console.log('Report load cancelled');
return null;
}
throw err;
}
}Adding timeouts with AbortSignal.timeout()
fetch() has no timeout option. A request to a server that never answers can hang for a long time, and the length depends on the browser and the operating system. You set a deadline by passing a signal that aborts on a timer.
AbortSignal.timeout(ms) returns a signal that aborts itself after ms milliseconds. On a timeout the rejection is a DOMException named 'TimeoutError', not 'AbortError'. That difference lets you tell "too slow" apart from "cancelled on purpose".
async function fetchWithTimeout(url, ms) {
try {
const response = await fetch(url, { signal: AbortSignal.timeout(ms) });
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return await response.json();
} catch (err) {
if (err.name === 'TimeoutError') {
throw new Error(`Request to ${url} timed out after ${ms} ms`);
}
throw err;
}
}
fetchWithTimeout('https://api.example.com/users', 5000)
.then((users) => console.log(users))
.catch((err) => console.error(err.message));The timeout covers the whole operation, including the body download, because the same signal applies to both. A large file on a slow connection can time out after the headers arrived with status 200. Pick the timeout for the full transfer, not only for the server's first byte.
The older setTimeout pattern
Before AbortSignal.timeout() existed, people built timeouts by hand. You will still see this in older code:
async function fetchWithManualTimeout(url, ms) {
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), ms);
try {
const response = await fetch(url, { signal: controller.signal });
return await response.json();
} finally {
clearTimeout(timer);
}
}It works, but it has two drawbacks. The rejection is named AbortError, so you cannot tell a timeout apart from a manual cancel. And if you forget clearTimeout, a timer keeps running after the request finished. Use AbortSignal.timeout() in new code. If you need the manual version, call controller.abort(new DOMException('Timed out', 'TimeoutError')) to keep the error names distinct.
Combining a user cancel with a timeout
A request often needs both: a Cancel button and a deadline. A fetch() call accepts only one signal. AbortSignal.any() takes an array of signals and returns a new signal that aborts as soon as any of them aborts. The combined signal's reason is the reason of whichever signal fired first, so the error name still tells you what happened.
const controller = new AbortController();
document.querySelector('#cancel')?.addEventListener('click', () => controller.abort());
const signal = AbortSignal.any([
controller.signal,
AbortSignal.timeout(8000)
]);
try {
const response = await fetch('https://api.example.com/export', { signal });
const data = await response.json();
console.log('Export ready', data);
} catch (err) {
if (err.name === 'AbortError') console.log('User cancelled');
else if (err.name === 'TimeoutError') console.log('Server too slow');
else throw err;
}AbortSignal.any() and AbortSignal.timeout() are newer than AbortController. Current browsers and Node.js 20 and later support both. Check your support targets before you rely on them.
Abort reasons
abort() takes an optional argument, the reason. The reason becomes signal.reason, and fetch() rejects with that exact value instead of the default AbortError.
const controller = new AbortController();
const pending = fetch('https://api.example.com/users', { signal: controller.signal });
controller.abort(new Error('Superseded by a newer search'));
pending.catch((err) => console.log(err.message)); // 'Superseded by a newer search'This is a common source of bugs. If some code aborts with a custom reason, a check for err.name === 'AbortError' no longer matches, and the cancellation is reported as a real error. A safer check asks the signal itself:
function wasCancelled(err, signal) {
return signal.aborted && err === signal.reason;
}Classifying a failed request
Once cancellation is in the picture, a rejected fetch can mean four different things. Each needs a different response in the UI.
| What happened | How to detect it | Typical handling |
|---|---|---|
| Cancelled on purpose | `err.name === 'AbortError'` or `err === signal.reason` | Ignore it silently |
| Deadline passed | `err.name === 'TimeoutError'` | Show "taking too long", offer a retry |
| Network failure | `TypeError` from `fetch()` | Show "check your connection" |
| HTTP error status | Promise resolved, `response.ok === false` | Show a message based on the status |
A practical pattern: cancelling stale searches
Search-as-you-type has a known race condition. The user types "fe", then "fetch". If the response for "fe" arrives after the one for "fetch", the old results overwrite the new ones. If you cancel the previous request whenever a new one starts, only the latest response can ever reach the screen.
let currentController = null;
async function search(query) {
currentController?.abort();
const controller = new AbortController();
currentController = controller;
try {
const url = `https://api.example.com/search?q=${encodeURIComponent(query)}`;
const response = await fetch(url, {
signal: AbortSignal.any([controller.signal, AbortSignal.timeout(5000)])
});
if (!response.ok) throw new Error(`HTTP ${response.status}`);
const results = await response.json();
console.log(`Results for "${query}":`, results);
} catch (err) {
if (err.name === 'AbortError') return; // a newer search replaced this one
console.error(`Search for "${query}" failed:`, err.message);
}
}
search('fe');
search('fetch'); // aborts the 'fe' requestGotchas
Aborting does not undo server work
An abort stops the browser from waiting. It does not tell the server to roll anything back. If the request body was already sent, a POST that creates an order may have succeeded on the server, even though your code saw an AbortError. Do not treat a cancelled or timed-out write as "nothing happened". Use idempotency keys or check the server state before retrying a write.
Reusing a controller across requests
Creating one controller at module level and using it for every request works until the first abort(). After that, every later request fails at once. Create one controller per operation.
Swallowing every error as a cancel
A catch block that returns quietly for any error hides real failures. Return silently only for errors you identified as cancellations, and rethrow the rest.
Listening to the signal in your own code
Your own async functions can respect the same signal. Check signal.aborted, call signal.throwIfAborted() between steps, or listen with signal.addEventListener('abort', handler, { once: true }). Then a single cancel stops the whole operation, not only the network part.
async function loadAndProcess(url, signal) {
const response = await fetch(url, { signal });
const items = await response.json();
const out = [];
for (const item of items) {
signal.throwIfAborted(); // stop CPU work too
out.push({ ...item, processed: true });
}
return out;
}Exercise
A function wraps its fetch in try/catch and ends with return response.json(); (no await). A 2-second AbortSignal.timeout() fires while the body is still downloading. Does the function's catch block run? Why or why not?
Show answer
No. Without await, the function returns the pending json() promise before it settles, so the try block has already exited. The TimeoutError rejects the returned promise and reaches the caller instead. Writing return await response.json(); keeps the rejection inside the try so the catch block can handle it.
Exercise
You combine a Cancel button's controller and a 10-second timeout with AbortSignal.any(). Your catch block checks only err.name === 'AbortError' and ignores those errors. Elsewhere, the cancel handler was changed to controller.abort(new Error('User left page')). What goes wrong, and how do you fix it?
Show answer
fetch now rejects with the custom Error, whose name is 'Error', so the check fails and a deliberate cancel is reported as a failure. Fix it by comparing against the signal: treat the error as a cancel when signal.aborted && err === signal.reason, or check controller.signal.aborted directly. Then handle TimeoutError separately.
Exercise
Write a function fetchJsonWithDeadline(url, ms, userSignal) that aborts on either a user signal or a timeout, returns parsed JSON, throws on a non-ok status, returns null when the user cancelled, and throws an Error with the message 'Timed out' on a timeout.
Show answer
async function fetchJsonWithDeadline(url, ms, userSignal) { const signal = AbortSignal.any([userSignal, AbortSignal.timeout(ms)]); try { const response = await fetch(url, { signal }); if (!response.ok) throw new Error(HTTP ${response.status}); return await response.json(); } catch (err) { if (userSignal.aborted) return null; if (err.name === 'TimeoutError') throw new Error('Timed out'); throw err; } }