Not every task should run to the end. A user types a new search before the old results arrive, closes a dialog while it is loading, or a server is so slow that waiting longer is pointless. JavaScript’s standard way to cancel work is the AbortController. It produces a signal that you pass to fetch, event listeners and your own functions; one call to abort() stops them all.
In this lesson you will learn
- Creating a controller and passing its
signal - Making your own functions cancellable
- Time limits with
AbortSignal.timeout() - Removing event listeners with a signal
- Cancelling
fetchrequests and handling the errors
You should know promises and async/await, timers and fetch.
Cancelling a Task
"use strict";
// A pretend download that takes ms milliseconds and can be cancelled
function download(name, ms, signal) {
return new Promise((resolve, reject) => {
if (signal?.aborted) return reject(signal.reason);
const timer = setTimeout(() => resolve(name + " downloaded"), ms);
signal?.addEventListener("abort", () => {
clearTimeout(timer); // stop the work
reject(signal.reason); // and report why
}, { once: true });
});
}
async function main() {
// 1. Cancel by hand with an AbortController
const controller = new AbortController();
const job = download("results.pdf", 500, controller.signal);
setTimeout(() => controller.abort(), 100); // e.g. the user pressed Cancel
try {
console.log(await job);
} catch (err) {
console.log("1:", err.name, "-", err.message);
}
// 2. Give up automatically after a time limit
try {
console.log(await download("video.mp4", 500, AbortSignal.timeout(150)));
} catch (err) {
console.log("2:", err.name); // TimeoutError
}
// 3. A fast job finishes before the limit
console.log("3:", await download("notes.txt", 50, AbortSignal.timeout(150)));
// 4. Your own reason
const c2 = new AbortController();
c2.abort(new Error("Page closed"));
try {
await download("map.png", 100, c2.signal);
} catch (err) {
console.log("4:", err.message, "| aborted:", c2.signal.aborted);
}
}
main();
Output
1: AbortError - This operation was aborted
2: TimeoutError
3: notes.txt downloaded
4: Page closed | aborted: true
new AbortController()has two parts:controller.signal, which you hand to the work, andcontroller.abort(), which you call to cancel it.- To make a function cancellable, check
signal.abortedbefore starting, then listen for the signal’sabortevent. Here the listener clears the timer and rejects the promise withsignal.reason. - Calling
abort()with no argument gives anAbortError. The exact message wording differs between Node.js and browsers, so checkerr.name, never the message. AbortSignal.timeout(150)creates a signal that aborts by itself after 150 milliseconds, with aTimeoutError. If the job finishes first, as the 50ms download does, nothing happens.abort(reason)can pass your own reason, such as anError, which becomes the rejection value.signal?.addEventListeneruses optional chaining, so the function also works when no signal is given.
Removing Listeners with a Signal
"use strict";
// One signal can cancel several things at once, including event listeners
const button = new EventTarget(); // stands in for a DOM button
const controller = new AbortController();
const { signal } = controller;
let clicks = 0;
button.addEventListener("click", () => {
clicks++;
console.log("click", clicks);
}, { signal }); // removed automatically on abort
// A second listener on another target, sharing the same signal
const page = new EventTarget(); // stands in for window
page.addEventListener("resize", () => console.log("resized"), { signal });
page.dispatchEvent(new Event("resize"));
signal.addEventListener("abort", () => {
console.log("Stopped:", signal.reason);
});
for (let i = 0; i < 3; i++) button.dispatchEvent(new Event("click"));
controller.abort("user left the page");
button.dispatchEvent(new Event("click")); // both listeners are gone:
page.dispatchEvent(new Event("resize")); // nothing more is printed
console.log("Total clicks:", clicks);
// In a browser, fetch accepts the same signal:
// const res = await fetch(url, { signal: AbortSignal.timeout(5000) });
// and an aborted fetch rejects with an AbortError or TimeoutError.
Output
resized
click 1
click 2
click 3
Stopped: user left the page
Total clicks: 3
- Passing
{ signal }as an option toaddEventListenerremoves the listener automatically when the signal aborts. You no longer need to keep a reference to the handler just to callremoveEventListener. - One signal can control many listeners on many targets. This is ideal for a component, such as a dialog, that sets up several listeners and must remove them all when it closes.
EventTargetis the same base class that DOM elements andwindowuse, so the code behaves the same in a browser.
Cancelling fetch
let controller = null;
async function search(text) {
controller?.abort(); // cancel the previous search, if any
controller = new AbortController();
// stop when a newer search starts OR after 5 seconds, whichever comes first
const signal = AbortSignal.any([controller.signal, AbortSignal.timeout(5000)]);
try {
const res = await fetch("/api/search?q=" + encodeURIComponent(text), { signal });
showResults(await res.json());
} catch (err) {
if (err.name === "AbortError") return; // replaced by a newer search: ignore
if (err.name === "TimeoutError") showMessage("The server is too slow, try again.");
else throw err;
}
}
- This pattern prevents an old, slow response from overwriting newer results, a common bug in search boxes.
AbortSignal.any([...])combines signals: the result aborts as soon as any of them does.- Aborting after the response has fully arrived has no effect. Aborting while the body is still being read makes
res.json()reject instead.
Common Mistakes
- Reusing an aborted controller. Once aborted, a signal stays aborted; create a new controller for each new task.
- Showing an error message for a deliberate cancel. Check for
AbortErrorand stay quiet. - Forgetting to stop the actual work in your own functions. Rejecting the promise is not enough if a timer or loop keeps running.
- Testing the error message text instead of
err.name.
Practice Exercises
Exercise 1. Write fetchJSON(url, ms) that fetches JSON but gives up after ms milliseconds.
Show answer
async function fetchJSON(url, ms) {
const res = await fetch(url, { signal: AbortSignal.timeout(ms) });
if (!res.ok) throw new Error("HTTP " + res.status);
return res.json();
}
Exercise 2. A popup adds a keydown listener on document and a click listener on window. Make both disappear when the popup closes.
Show answer
const controller = new AbortController();
document.addEventListener("keydown", onKey, { signal: controller.signal });
window.addEventListener("click", onClick, { signal: controller.signal });
function closePopup() {
popup.hidden = true;
controller.abort(); // removes both listeners
}
Frequently Asked Questions
Does aborting a fetch stop the server?
It closes the connection from the browser’s side, so your code stops waiting and no more data is downloaded. The server may already have done the work, so do not rely on aborting to undo something like a payment.
Can promises be cancelled without AbortController?
No. A promise has no built-in cancel method. AbortController is the standard way to tell the work behind a promise to stop, and libraries and APIs increasingly accept a signal option.
Summary
- An
AbortControllergives asignalto pass around and anabort()method to cancel. AbortSignal.timeout(ms)adds time limits;AbortSignal.anycombines signals.- Listeners added with
{ signal }are removed on abort. - Check
err.nameforAbortErrorandTimeoutError.
