AbortController
Published by Brayan K
AbortController is a built-in object that produces a reusable signal you hand to async work, so calling its abort() method can cancel a fetch, timer, or any operation listening to that signal.
Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
Share a signal, but never reset an aborted signal
One signal can be handed to several cooperating operations during a shared lifetime. Once aborted, it stays aborted forever; a new operation that needs a fresh cancellation lifetime needs a new controller. The introduction’s reusable signal means shared observation, not a resettable cancellation token.
const controller = new AbortController();
const firstReason = new Error("screen closed");
// Every observer sees the same signal and the first cancellation reason.
console.log(controller.signal.aborted);
controller.abort(firstReason);
controller.abort(new Error("later reason"));
console.log(controller.signal.aborted, controller.signal.reason === firstReason);
try { controller.signal.throwIfAborted(); }
catch (error) { console.log(error.name, error.message); }
// ✅ Expected output:
// false
// true true
// Error screen closedconst signal = AbortSignal.abort(new Error("operation cancelled"));
signal.throwIfAborted();
// ✅ Expected error:
// Error: operation cancelledThe controller owns the ability to abort; consumers usually receive only its signal. Calling abort with no explicit reason supplies an AbortError DOMException. A custom reason can be any JavaScript value, so code must not assume every rejection is an Error object.
const standard = new AbortController();
standard.abort();
console.log(standard.signal.reason.name);
const custom = new AbortController();
custom.abort("no longer needed");
try { custom.signal.throwIfAborted(); }
catch (reason) { console.log(typeof reason, reason); }
// ✅ Expected output:
// AbortError
// string no longer neededThe signal changes immediately; promise observers run later
const events = [];
const controller = new AbortController();
const result = new Promise((resolve, reject) => {
controller.signal.addEventListener("abort", () => {
events.push("listener");
reject(controller.signal.reason);
}, { once: true });
});
const observed = result.catch(() => events.push("catch"));
events.push("before");
controller.abort(new Error("cancelled"));
events.push("after");
await observed;
console.log(events.join(", "));
// ✅ Expected output:
// before, listener, after, catchconst controller = new AbortController();
controller.abort("already stopped");
let calls = 0;
controller.signal.addEventListener("abort", () => calls++);
console.log(controller.signal.aborted, calls);
// ✅ Expected output:
// true 0An abort-aware API checks signal.aborted before starting work, then observes a future abort while work is active. Listening only for the event misses an already-aborted signal. Use throwIfAborted for a deliberate synchronous checkpoint, or reject with signal.reason in a promise API.
Cancellation requires cooperation and does not undo committed effects
const controller = new AbortController();
const effects = [];
async function ignoresSignal() {
await Promise.resolve();
effects.push("saved");
return "done";
}
const result = ignoresSignal();
controller.abort();
console.log(await result, effects.join(", "));
// ✅ Expected output:
// done savedconst controller = new AbortController();
const events = [];
let release;
const gate = new Promise(resolve => { release = resolve; });
async function work(signal) {
signal.throwIfAborted();
events.push("started");
await gate;
signal.throwIfAborted();
events.push("committed");
}
const observed = work(controller.signal).catch(reason => events.push(reason.message));
controller.abort(new Error("cancelled"));
release();
await observed;
console.log(events.join(", "));
// ✅ Expected output:
// started, cancelledThe signal cannot interrupt a long synchronous calculation in the same thread, nor can it erase an earlier mutation or server-side action. Chunked work needs explicit checkpoints and opportunities for other tasks to run. JavaScript Performance Optimization Techniques owns chunking; Web Workers (Background Threads) owns moving CPU work off the main thread.
Fetch accepts a signal, but a client cancellation is not proof that the server did not process a request. Advanced Fetch API Patterns (Retry, Timeout, AbortController) owns response-body and retry behavior; Async Iterators & for-await-of explains why returning a generator does not interrupt an active awaited operation.
Compose cancellation lifetimes without mutating their parents
const screen = new AbortController(), manual = new AbortController();
const combined = AbortSignal.any([screen.signal, manual.signal]);
manual.abort("user stopped");
screen.abort("screen closed");
console.log(combined.aborted, combined.reason);
console.log(manual.signal.reason, screen.signal.reason);
// ✅ Expected output:
// true user stopped
// user stopped screen closedconst first = AbortSignal.abort("first"), second = AbortSignal.abort("second");
const combined = AbortSignal.any([second, first]);
console.log(combined.aborted, combined.reason);
const empty = AbortSignal.any([]);
console.log(empty.aborted);
// ✅ Expected output:
// true second
// falseconst signal = AbortSignal.timeout(5000);
console.log(signal instanceof AbortSignal, signal.aborted);
// ✅ Expected output:
// true falseAbortSignal.timeout produces a TimeoutError reason when its deadline fires. The example checks creation only and makes no timing or firing claim. In browsers its timeout measures active time and may pause while a document or worker is suspended. It is not a guaranteed wall-clock service deadline. Combining a timeout signal with a user signal does not abort either source controller.
A Promise.race timeout merely changes what the caller awaits unless it also signals the underlying operation. Promise Combinators (all, race, allSettled, any) owns that distinction. Signals let an operation cooperate; they do not turn an ignored signal into automatic cancellation.
Release listeners on every completion path
const controller = new AbortController();
let calls = 0;
const onAbort = () => calls++;
controller.signal.addEventListener("abort", onAbort, { once: true });
// This operation finished normally, before cancellation.
controller.signal.removeEventListener("abort", onAbort);
controller.abort();
console.log(calls);
// ✅ Expected output:
// 0once removes an abort listener after that event fires. It does not remove the listener merely because unrelated work completed successfully. A custom promise API should remove both its work listener and its abort listener when either outcome wins. JavaScript Memory Management & Garbage Collection owns resource lifetime beyond this signal-specific pattern.
Guided exercise: observe the first cancellation reason
Fill the literal hints. The second abort must leave the first reason intact, and a checkpoint must throw that same reason.
const controller = new ___(); // 👉 replace ___ with AbortController
controller.abort("closed");
controller.abort("later");
console.log(controller.signal.___); // 👉 replace ___ with reason
try { controller.signal.___(); } // 👉 replace ___ with throwIfAborted
catch (reason) { console.log(reason); }
// ✅ Expected output:
// closed
// closedBrief: an event wait that cancels cleanly
Implement async waitForEvent(target, type, signal). Accept an EventTarget from this realm, a lowercase event name of 1–32 ASCII letters/digits/hyphens beginning with a letter, and an optional AbortSignal from this realm. Invalid arguments reject with TypeError. Work with ordinary built-in event targets and signals, not monkey-patched listener methods.
Resolve with the exact first matching Event object, or reject with the exact signal.reason if cancellation wins. An already-aborted signal must reject without attaching listeners. Remove both listeners after success or cancellation, and ignore subsequent events or aborts. Do not abort a controller you do not own. Returning the Event does not freeze it or preserve temporary dispatch fields such as currentTarget.
async function waitForEvent(target, type, signal = undefined) {
if (!(target instanceof EventTarget)) throw new TypeError("target must be an EventTarget");
if (typeof type !== "string" || !/^[a-z][a-z0-9-]{0,31}$/.test(type)) throw new TypeError("invalid event type");
if (signal !== undefined && !(signal instanceof AbortSignal)) throw new TypeError("signal must be an AbortSignal");
return new Promise((resolve, reject) => {
if (signal?.aborted) { reject(signal.reason); return; }
let settled = false;
const cleanup = () => {
target.removeEventListener(type, onEvent);
signal?.removeEventListener("abort", onAbort);
};
function onEvent(event) {
if (settled) return;
settled = true;
cleanup();
resolve(event);
}
function onAbort() {
if (settled) return;
settled = true;
cleanup();
reject(signal.reason);
}
target.addEventListener(type, onEvent, { once: true });
signal?.addEventListener("abort", onAbort, { once: true });
});
}
const target = new EventTarget(), controller = new AbortController();
const pending = waitForEvent(target, "ready", controller.signal);
const event = new Event("ready");
target.dispatchEvent(event);
console.log(await pending === event);
controller.abort("too late");
const cancelled = new AbortController();
const reason = { code: "closed" };
const observed = waitForEvent(target, "ready", cancelled.signal).catch(error => error === reason);
cancelled.abort(reason);
console.log(await observed);
const preAborted = AbortSignal.abort("already");
try { await waitForEvent(target, "ready", preAborted); }
catch (error) { console.log(error); }
// ✅ Expected output:
// true
// true
// alreadyThis wait has no default timeout. If neither an event nor cancellation occurs, its promise remains pending. A caller can provide an appropriate composed signal, while the operation still owns its own listener cleanup.
Practice quiz
What does this complete program print? const c=new AbortController();c.abort("first");c.abort("second");console.log(c.signal.reason);
- first
- second
- undefined
- AbortError
Answer: first. The first abort fixes the reason.
What does this complete program print? const c=new AbortController();c.abort();console.log(c.signal.aborted,c.signal.reason.name);
- false AbortError
- true AbortError
- true Error
- false Error
Answer: true AbortError. A default abort creates an AbortError and permanently changes state.
What does this complete program print? const c=new AbortController();c.abort();let n=0;c.signal.addEventListener("abort",()=>n++);console.log(n);
- 1
- 2
- 0
- TypeError
Answer: 0. Late listeners do not receive a replay.
What does this complete program print? const c=new AbortController();const events=[];c.signal.addEventListener("abort",()=>events.push("event"));c.abort();events.push("after");console.log(events.join(","));
- after,event
- after
- event
- event,after
Answer: event,after. Abort dispatch happens during the abort call.
What does this complete program print? const reason={code:"stop"};const signal=AbortSignal.abort(reason);try{signal.throwIfAborted();}catch(error){console.log(error===reason);}
- true
- false
- undefined
- TypeError
Answer: true. The exact custom reason is thrown.
What does this complete program print? const a=new AbortController(),b=new AbortController();const s=AbortSignal.any([a.signal,b.signal]);b.abort("b");console.log(s.reason,a.signal.aborted);
- b true
- b false
- a false
- undefined false
Answer: b false. The combined signal adopts the reason without aborting the other source.
What does this complete program print? console.log(AbortSignal.any([]).aborted);
- true
- undefined
- false
- TypeError
Answer: false. There is no source that can abort this empty combination.
What does this complete program print? const c=new AbortController();let n=0;const fn=()=>n++;c.signal.addEventListener("abort",fn,{once:true});c.signal.removeEventListener("abort",fn);c.abort();console.log(n);
- 1
- 2
- TypeError
- 0
Answer: 0. Explicit removal prevents a later cancellation callback after success.
Continue this course
- Previous: Async Iterators & for-await-of
- Next: Web Workers (Background Threads) — Run CPU-heavy work off the main thread to keep the UI responsive
- Quick reference: JavaScript cheat sheet