The JavaScript AbortController object
An AbortController lets you cancel asynchronous operations. You create one, pass its signal to an operation like fetch(), and call controller.abort() to cancel it. The aborted operation rejects with an AbortError. The same signal can also remove event listeners and cancel timers.
Overview
AbortController is the standard way to cancel an in-progress async operation. You create a controller, which exposes a signal, and you pass that signal to an operation that supports it. Later, calling controller.abort() cancels the operation — the signal fires an abort event and any work tied to it stops.
Its headline use is canceling a fetch(): fetch(url, { signal }), then controller.abort() to cancel the request (which rejects with an AbortError you can catch and ignore). This is essential for things like search-as-you-type, where you want to cancel the previous request when a new one starts, and for adding a timeout — abort after N milliseconds. (There's even a shortcut, AbortSignal.timeout(ms), for that.)
The same signal works beyond fetch. addEventListener() accepts a { signal } option, so calling abort() removes the listener — a clean way to tear down many listeners at once. One controller can coordinate canceling several operations together. Note a controller is single-use: once aborted, it stays aborted; create a new one for the next operation.
Syntax
const controller = new AbortController();
const { signal } = controller;
fetch(url, { signal }); // cancelable request
el.addEventListener("click", fn, { signal }); // removable listener
controller.abort(); // cancel everything tied to the signal
Example
// cancel a fetch after 5 seconds
const controller = new AbortController();
const timer = setTimeout(() => controller.abort(), 5000);
try {
const res = await fetch('/api/data', { signal: controller.signal });
const data = await res.json();
clearTimeout(timer);
} catch (err) {
if (err.name === 'AbortError') console.log('request canceled');
else throw err;
}
Best practices
- Pass
controller.signalto fetch() and callabort()to cancel requests (e.g. search-as-you-type). - Catch the resulting
AbortErrorand ignore it — an abort isn't a real error. - Use
{ signal }with addEventListener() to remove listeners by aborting. - A controller is single-use — create a fresh one for each new operation.
Frequently asked questions
How do I cancel a fetch request?
AbortController, pass controller.signal to fetch(), and call controller.abort() to cancel it.What happens to an aborted fetch?
AbortError. Catch and ignore it, since an intentional abort isn't a failure.Can AbortController remove event listeners?
How do I add a timeout to a fetch?
AbortSignal.timeout(ms) as the signal.