
Stop Stuck Requests and Leaked Listeners: A Practical Guide to JavaScript AbortController
AbortController is one of the most underused built-ins in modern JavaScript. It lets you cancel a fetch, time out a network call, and tear down event listeners — all from a single, composable signal. Here is how it actually works, with runnable snippets you can paste today.
The mental model
An AbortController has two parts:
controller.signal— a read-onlyAbortSignalyou pass into anything that knows how to listen for cancellation.controller.abort()— flips the signal to “aborted”, which notifies every listener at once.
const controller = new AbortController();
const { signal } = controller;
// later, when you want to cancel:
controller.abort();
console.log(signal.aborted); // true
That is the whole primitive. Everything below is built on top of it.
Canceling a fetch
fetch accepts a signal in its options. Call abort() and the promise rejects with a DOMException named AbortError.
const controller = new AbortController();
fetch("https://api.example.com/data", { signal: controller.signal })
.then((res) => res.json())
.catch((err) => {
if (err.name === "AbortError") {
console.log("Request was canceled");
} else {
throw err; // a real network error
}
});
// cancel it before it finishes
controller.abort();
Always check err.name === "AbortError" — catching the error and re-throwing anything else keeps genuine failures visible.
Timing out a request (the clean way)
Instead of juggling setTimeout + clearTimeout, use AbortSignal.timeout(). It creates a signal that aborts itself after N milliseconds:
const res = await fetch("https://api.example.com/slow", {
signal: AbortSignal.timeout(5000), // auto-aborts after 5s
});
// You can combine your own controller with a timeout too:
const controller = new AbortController();
const combined = AbortSignal.any([
controller.signal,
AbortSignal.timeout(5000),
]);
fetch(url, { signal: combined });
AbortSignal.any() (modern browsers and Node 20+) fires as soon as any of its inputs aborts — handy when you want both a manual cancel and a deadline.
Cleaning up event listeners
AbortSignal is also a first-class way to remove listeners. Pass it as the signal option and abort() removes every listener attached with that signal at once — no more storing handler references:
const controller = new AbortController();
window.addEventListener("resize", onResize, { signal: controller.signal });
document.addEventListener("click", onClick, { signal: controller.signal });
socket.addEventListener("message", onMessage, { signal: controller.signal });
// one line removes ALL of them
controller.abort();
This is the cleanest way to avoid listener leaks in components, single-page apps, and long-lived connections.
Avoiding race conditions in searches
A classic bug: a user types fast, the first (slower) request resolves after the second, overwriting fresh results with stale ones. Abort the previous request on each new keystroke:
let controller;
async function search(query) {
controller?.abort(); // cancel the in-flight request
controller = new AbortController();
try {
const res = await fetch(`/api/search?q=${query}`, {
signal: controller.signal,
});
render(await res.json());
} catch (err) {
if (err.name !== "AbortError") throw err; // ignore canceled ones
}
}
The abandoned request rejects with AbortError; we swallow it and keep only the latest response.
Gotchas worth remembering
- One signal is single-use. After
abort(), the signal stays aborted forever. If you need to cancel again later, create a newAbortController. - Aborting a finished request is safe. Calling
abort()afterfetchalready resolved does nothing and throws no error. - Do not reuse a controller across retries blindly. Start a fresh controller for each attempt, or combine per-attempt signals with
AbortSignal.any(). - Listen for the event too.
signal.addEventListener("abort", ...)lets your own code react to cancellation, not justfetch.
Takeaways
AbortController+AbortSignalis the standard way to cancelfetch, time out calls, and remove listeners.AbortSignal.timeout(ms)replaces manualsetTimeoutboilerplate.AbortSignal.any([...])merges multiple cancellation sources.- Passing
signaltoaddEventListenerremoves listener leaks with oneabort()call. - Always special-case
err.name === "AbortError"so real errors still surface.
That is it — a small API that quietly fixes three of the most common frontend bugs at once.