Sub topic 8
Cancelling Requests and Adding Timeouts
This chapter assumes you know async/await, try/catch, and how fetch() resolves to a Response that you check with response.ok. Earlier chapters covered those points. Here you will learn how to stop a request that is still running, either because the user no longer needs the result or because the server is taking too long.
Why fetch needs a cancel button
fetch() has no built-in timeout. If a server accepts the connection and then never answers, the Promise can stay pending for minutes. The browser's own limits decide when it finally fails. Pending requests also cause stale-data bugs. Say a user types "fe" and then "fetch" into a search box. If the "fe" response arrives last, it overwrites the newer results.
The fix is a signal. A signal is an AbortSignal object that you pass to fetch() in the signal option. When the signal fires, fetch stops the request and its Promise rejects.
AbortController: cancelling on demand
An AbortController owns a signal. You pass controller.signal to fetch. Calling controller.abort() later cancels every request that uses that signal.
const controller = new AbortController();
fetch('https://api.example.com/search?q=fetch', { signal: controller.signal })
.then((response) => response.json())
.then((data) => console.log(data))
.catch((err) => {
if (err.name === 'AbortError') {
console.log('Request was cancelled');
} else {
console.error('Request failed:', err);
}
});
controller.abort();The rejection is a DOMException whose name is 'AbortError'. Check err.name, not instanceof Error or the message text. A cancel is usually expected behaviour, so it should not trigger an error message for the user.
The signal also covers body reading. If you abort after the headers arrive but while response.json() is still reading, that call rejects with the same AbortError.
Cancelling the previous search
The usual pattern keeps one controller per request in progress and aborts the old one before starting a new one:
let currentController = null;
async function search(query) {
currentController?.abort();
currentController = new AbortController();
try {
const response = await fetch(
`https://api.example.com/search?q=${encodeURIComponent(query)}`,
{ signal: currentController.signal }
);
if (!response.ok) throw new Error(`HTTP ${response.status}`);
return await response.json();
} catch (err) {
if (err.name === 'AbortError') return null; // superseded by a newer search
throw err;
}
}Each call creates a fresh controller because aborting is permanent. Once a signal is aborted it stays aborted, and any later fetch that receives it rejects right away.
AbortSignal.timeout(): a deadline in one line
For timeouts you don't need a controller or setTimeout. AbortSignal.timeout(ms) returns a signal that aborts itself after ms milliseconds. The rejection's name is 'TimeoutError', which lets you tell a timeout apart from a manual cancel.
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;
}
}The deadline counts the whole operation, including reading the body inside the try, because the same signal stays attached until the body is read.
Combining a timeout with manual cancel
AbortSignal.any() takes several signals and returns one that fires when any of them fires:
const controller = new AbortController();
const signal = AbortSignal.any([controller.signal, AbortSignal.timeout(5000)]);
fetch('https://api.example.com/report', { signal })
.catch((err) => console.log(err.name)); // 'AbortError' or 'TimeoutError'Common errors
| Mistake | What happens | Fix |
|---|---|---|
| Reusing an aborted controller | New requests reject immediately | Create a new `AbortController` per request |
| Treating `AbortError` as a failure | Users see errors for cancels they caused | Check `err.name` and ignore or handle quietly |
| Calling `abort(reason)` with a custom value | fetch rejects with that value, not an `AbortError` | Check for your own reason, or call `abort()` with no argument |
| Clearing a `setTimeout` too early | Timeout no longer covers `response.json()` | Use `AbortSignal.timeout()` and keep the body read inside the same `try` |
Exercise
A request uses signal: AbortSignal.timeout(3000). The server sends headers after 1 second, but the JSON body takes 4 more seconds to stream. What happens when you await response.json(), and what is err.name?
Show answer
The fetch() Promise resolves after 1 second. The response.json() call then rejects when the 3-second deadline passes, because the signal also covers body reading. The error's name is 'TimeoutError'.
Exercise
Why does this code fail on the second call? const c = new AbortController(); c.abort(); fetch(url, { signal: c.signal });
Show answer
The signal is already aborted and aborting is permanent. fetch rejects immediately with an AbortError without sending the request. Create a new AbortController for each request.