Canceling and Timeouts
Promises have no built-in way to cancel the work behind them. When a user types a new search term, leaves a page, or clicks Cancel, the old requests keep running and their results arrive late, sometimes overwriting newer data. AbortController solves this: it creates an AbortSignal that you pass to fetch, event listeners, timers and your own functions; calling controller.abort() tells all of them to stop. AbortSignal.timeout(ms) and AbortSignal.any([...]) build timeouts and combined signals in one line.
In One Minute
const controller = new AbortController()gives youcontroller.signalandcontroller.abort(reason?).- Pass the signal to
fetch(url, { signal }); aborting rejects the fetch with anAbortError. AbortSignal.timeout(ms)aborts automatically afterms, with aTimeoutError.AbortSignal.any([signalA, signalB])aborts when either does: a user Cancel or a timeout.- Make your own functions cancelable by checking
signal.aborted, callingsignal.throwIfAborted(), or listening for theabortevent.
AbortController and AbortSignal
| Member | Description |
|---|---|
new AbortController() | It is used to create a controller that owns one signal. |
controller.signal | The AbortSignal to pass to operations. |
controller.abort(reason?) | It is used to abort; the reason defaults to a DOMException named AbortError. |
signal.aborted | true once aborted. |
signal.reason | Why it was aborted. |
signal.throwIfAborted() | It is used to throw signal.reason if already aborted. |
signal.addEventListener("abort", fn) | It is used to run code when it aborts. |
AbortSignal.timeout(ms) | A signal that aborts after ms with a TimeoutError. |
AbortSignal.any(signals) | A signal that aborts when any of the given signals abort. |
AbortSignal.abort(reason?) | An already-aborted signal. |
const controller = new AbortController();
const { signal } = controller;
signal.addEventListener("abort", () => console.log("abort event, reason:", signal.reason.name));
console.log(signal.aborted);
controller.abort();
console.log(signal.aborted, signal.reason.name);
controller.abort();
try {
signal.throwIfAborted();
} catch (err) {
console.log("throwIfAborted threw", err.name);
}false
abort event, reason: AbortError
true AbortError
throwIfAborted threw AbortErrorA signal aborts once; calling abort() again does nothing. One signal can be shared by many operations, so one call cancels them all.
Canceling fetch
{ "total": 655 }<button id="cancel">Cancel</button>
<script type="module">
const controller = new AbortController();
document.querySelector("#cancel").addEventListener("click", () => controller.abort());
try {
const res = await fetch("/api/report.json", { signal: controller.signal });
console.log("loaded", (await res.json()).total);
} catch (err) {
if (err.name === "AbortError") console.log("Report request canceled");
else console.log("Failed:", err.message);
}
</script>Report request canceledExplanation: the slow report request was still in progress when the checker clicked Cancel. controller.abort() stopped the network request and rejected the fetch promise with an AbortError. Check err.name to tell a deliberate cancellation (usually not an error worth showing) from a real failure.
Timeouts with AbortSignal.timeout
AbortSignal.timeout(ms) creates a signal that aborts by itself, with a reason named TimeoutError:
<script type="module">
try {
await fetch("/api/report.json", { signal: AbortSignal.timeout(200) });
} catch (err) {
console.log(err.name, "|", err.message);
}
</script>TimeoutError | signal timed outUnlike Promise.race with a timer, this actually stops the request, freeing the connection.
Combining Signals with AbortSignal.any
Real interfaces need several reasons to stop: the user clicks Cancel, or a timeout passes, or the component closes. AbortSignal.any combines them into one signal:
<button id="cancel">Cancel</button>
<script type="module">
const userCancel = new AbortController();
document.querySelector("#cancel").addEventListener("click", () => userCancel.abort());
const signal = AbortSignal.any([userCancel.signal, AbortSignal.timeout(250)]);
try {
await fetch("/api/report.json", { signal });
} catch (err) {
const why = err.name === "TimeoutError" ? "took too long" : err.name === "AbortError" ? "canceled by the user" : err.message;
console.log(`Stopped: ${why}`);
}
</script>Stopped: took too longNobody clicked Cancel, so the timeout fired first, and the combined signal's reason is the timeout's TimeoutError.
Making Your Own Functions Cancelable
Any async function can accept a signal. Check it between steps, and pass it on to anything that supports it:
function sleep(ms, { signal } = {}) {
return new Promise((resolve, reject) => {
signal?.throwIfAborted();
const timer = setTimeout(resolve, ms);
signal?.addEventListener("abort", () => {
clearTimeout(timer);
reject(signal.reason);
}, { once: true });
});
}
async function processPayments(ids, { signal } = {}) {
const done = [];
for (const id of ids) {
signal?.throwIfAborted();
await sleep(10, { signal });
done.push(id);
}
return done;
}
const controller = new AbortController();
setTimeout(() => controller.abort(), 35);
try {
await processPayments([1, 2, 3, 4, 5, 6], { signal: controller.signal });
} catch (err) {
console.log("stopped:", err.name);
}
console.log(await processPayments([1, 2], {}));stopped: AbortError
[1, 2]Explanation: sleep rejects as soon as the signal aborts, clearing its timer so nothing is left running. processPayments checks the signal before each item and passes it on to sleep, so the abort after 35 ms stops the loop partway through. Making the signal optional ({ signal } = {} and signal?.) keeps the function easy to call when cancellation isn't needed.
Other APIs That Accept a Signal
| API | Effect of aborting |
|---|---|
fetch(url, { signal }) | Cancels the request; rejects with the signal's reason |
addEventListener(type, fn, { signal }) | Removes the listener |
Node.js node:timers/promises (setTimeout(ms, value, { signal })) | Cancels the timer |
Node.js fs.readFile(path, { signal }), child_process, stream.pipeline | Cancels the operation |
ReadableStream piping (pipeTo(dest, { signal })) | Stops the pipe |
Avoiding Stale Results
The most common real bug cancellation fixes: a user types quickly, several searches run, and a slow, older response arrives after a newer one, showing results for the wrong text. Abort the previous request whenever a new one starts:
const fakeSearch = (term, { signal }) =>
new Promise((resolve, reject) => {
const timer = setTimeout(() => resolve(`results for "${term}"`), term.length === 1 ? 50 : 10);
signal.addEventListener("abort", () => { clearTimeout(timer); reject(signal.reason); }, { once: true });
});
let current;
async function search(term) {
current?.abort();
current = new AbortController();
try {
console.log(await fakeSearch(term, { signal: current.signal }));
} catch (err) {
if (err.name !== "AbortError") throw err;
console.log(`(search for "${term}" canceled)`);
}
}
await Promise.all([search("N"), search("Na"), search("Nav")]);(search for "N" canceled)
(search for "Na" canceled)
results for "Nav"Without the abort, the slow search for "N" would have finished last and overwritten the correct results for "Nav".
In Practice
The Fee Tracker's report panel combines everything: one controller for the panel's lifetime (closing the panel cancels all its work, including listeners), plus a timeout per request:
{ "byGrade": { "9": 165, "11": 85, "12": 300 } }<div id="panel"><p id="status">Loading...</p><button id="close">Close</button></div>
<script type="module">
const panel = new AbortController();
const status = document.querySelector("#status");
document.querySelector("#close").addEventListener("click", () => {
panel.abort(new DOMException("Panel closed", "AbortError"));
console.log("panel closed, aborted:", panel.signal.aborted);
}, { signal: panel.signal });
async function loadTotals() {
const signal = AbortSignal.any([panel.signal, AbortSignal.timeout(2000)]);
const res = await fetch("/api/totals.json", { signal });
return res.json();
}
try {
const { byGrade } = await loadTotals();
status.textContent = Object.entries(byGrade).map(([g, t]) => `Grade ${g}: $${t}`).join(", ");
console.log(status.textContent);
} catch (err) {
if (err.name !== "AbortError") status.textContent = "Couldn't load totals";
}
</script>Grade 9: $165, Grade 11: $85, Grade 12: $300
panel closed, aborted: trueThe close listener itself was registered with the panel's signal, so aborting also removes it: a second click would do nothing.
Common Mistakes
Treating AbortError as a failure. It's usually expected; don't show an error message for it.
Reusing an aborted controller. A signal aborts once. Create a new AbortController for each new operation.
Using Promise.race for timeouts on fetch. The request keeps running. Use AbortSignal.timeout.
Not passing the signal down. Inner calls keep running after the outer one is canceled. Pass { signal } through every layer.
Practice
Challenge: Write fetchJsonWithTimeout(url, ms, signal) that combines an optional caller signal with a timeout and returns parsed JSON, then call it on the served /api/totals.json.
Show solution
<script type="module">
async function fetchJsonWithTimeout(url, ms, signal) {
const signals = [AbortSignal.timeout(ms), ...(signal ? [signal] : [])];
const res = await fetch(url, { signal: AbortSignal.any(signals) });
if (!res.ok) throw new Error(`HTTP ${res.status}`);
return res.json();
}
const data = await fetchJsonWithTimeout("/api/totals.json", 1000);
console.log(Object.keys(data.byGrade).length, "grades");
</script>3 gradesKey Takeaways
| Task | Code |
|---|---|
| Create | const c = new AbortController() |
| Cancel a request | fetch(url, { signal: c.signal }); c.abort() |
| Timeout | { signal: AbortSignal.timeout(5000) } |
| Either reason | AbortSignal.any([c.signal, AbortSignal.timeout(5000)]) |
| Check inside a loop | signal.throwIfAborted() |
| Recognize cancellation | err.name === "AbortError" |
Was this tutorial helpful?