Sub topic 2
AbortController and AbortSignal in One Minute
This chapter assumes you know JavaScript functions and destructuring, promises with async/await, try/catch, and basic addEventListener usage. Every example runs in a modern browser console or in Node.js 18 or later, where AbortController and AbortSignal are globals.
The previous chapter covered why async work needs a way to stop. This chapter introduces the two objects the platform provides for that job. You will see how they split responsibility, what happens when you call abort(), and what rules govern their lifetime. Later chapters go deeper into each piece: reading signal state, listening for the abort event, and designing function APIs that accept a signal.
Two Objects, Two Roles
Cancellation in JavaScript uses a pair of objects:
- An
AbortControlleris the object that triggers cancellation. It has a single method that matters,abort(), and a single property,signal. - An
AbortSignalis the object that reports cancellation. It is read-only from the outside. Code can inspect it and listen to it, but cannot abort it.
You create the controller. The controller creates its signal. You keep the controller and hand the signal to whatever work you might want to stop.
const controller = new AbortController();
const signal = controller.signal;
console.log(signal instanceof AbortSignal); // true
console.log(signal instanceof EventTarget); // true
console.log(signal.aborted); // false
console.log(controller.signal === signal); // true, always the same objectThe split follows a capability pattern. Whoever holds the controller can cancel. Whoever holds only the signal can observe but not cancel. A function you call can never cancel work on its own initiative by aborting your signal, because it never receives the controller.
What abort() Does
Calling controller.abort() performs three steps, in this order:
- It sets
signal.abortedtotrue. - It sets
signal.reason. With no argument, the reason is aDOMExceptionwhosenameis"AbortError". - It dispatches an
abortevent on the signal, synchronously, beforeabort()returns.
const controller = new AbortController();
const { signal } = controller;
signal.addEventListener('abort', () => {
console.log('aborted:', signal.aborted); // true
console.log('reason:', signal.reason.name); // "AbortError"
}, { once: true });
controller.abort();Because the event fires synchronously, the two console.log lines inside the listener run before any code after controller.abort(). You can confirm the ordering:
const controller = new AbortController();
controller.signal.addEventListener('abort', () => {
console.log('2: listener runs');
});
console.log('1: before abort()');
controller.abort();
console.log('3: after abort()');The output is 1, 2, 3 in order. This matters when you write cleanup code. By the time abort() returns, every listener has already run. Any promise rejections those listeners triggered are still delivered later, as microtasks, like all promise callbacks.
The Lifetime Rules
A signal has a simple life with only two states, and it moves between them once.
These rules follow from that design:
| Rule | Consequence |
|---|---|
| Abort is one-way | There is no `reset()`. An aborted signal stays aborted. |
| Abort is idempotent | Calling `abort()` a second time does nothing: no new event, and the reason does not change. |
| One controller per operation | To retry or restart work, create a new `AbortController`. |
| One signal, many consumers | You can pass the same signal to several functions, and one `abort()` cancels them all. |
| Signals do not expire on their own | A signal from `new AbortController()` stays unaborted until someone calls `abort()`. Deadlines come from `AbortSignal.timeout()`, covered in a later chapter. |
Idempotence is easy to check:
const controller = new AbortController();
let events = 0;
controller.signal.addEventListener('abort', () => { events += 1; });
controller.abort(new Error('first'));
controller.abort(new Error('second'));
console.log(events); // 1
console.log(controller.signal.reason.message); // "first"Handing the Signal to Work
Built-in APIs already accept a signal, and that is where most developers first see these objects. fetch is the best-known example:
const controller = new AbortController();
fetch('https://example.com/', { signal: controller.signal })
.then((response) => console.log('status:', response.status))
.catch((err) => console.log('fetch failed:', err.name)); // "AbortError"
controller.abort();Because abort() runs before the request completes, the promise rejects with the signal's reason, and err.name is "AbortError".
Your own functions can accept a signal the same way. Here is a minimal async function that does work in steps and stops when the signal is aborted. It uses only signal.aborted, the simplest thing a signal offers:
const tick = () => new Promise((resolve) => setTimeout(resolve, 100));
async function countTo(limit, { signal } = {}) {
for (let i = 1; i <= limit; i += 1) {
if (signal?.aborted) {
console.log(`stopped at ${i - 1}`);
return;
}
console.log(i);
await tick();
}
console.log('done');
}
const controller = new AbortController();
countTo(10, { signal: controller.signal });
setTimeout(() => controller.abort(), 350);This prints 1 through 4 and then stopped at 4. The function checks the signal between steps, so the abort at 350 ms takes effect at the next check, around 400 ms. Cancellation is cooperative: the signal only reports that someone asked to stop. The function decides when to look and what stopping means.
Two parts of the design are deliberate. The signal arrives inside an options object, { signal }, matching fetch and other platform APIs. It is also optional, so signal?.aborted handles callers who pass nothing. The chapter on designing the API explains this convention in full. This version also returns quietly instead of rejecting, which is not what platform APIs do. Later chapters fix that.
The Surface Area at a Glance
The whole API is small. The table lists the members used throughout this tutorial. Each one has its own chapter later on.
| Member | On | Purpose |
|---|---|---|
| `new AbortController()` | constructor | Creates a controller and its signal. Takes no arguments. |
| `controller.signal` | controller | The associated `AbortSignal`. |
| `controller.abort(reason?)` | controller | Aborts the signal, optionally with a custom reason. |
| `signal.aborted` | signal | `true` once aborted. |
| `signal.reason` | signal | Why it was aborted; `undefined` until then. |
| `signal.throwIfAborted()` | signal | Throws `signal.reason` if aborted; otherwise does nothing. |
| `'abort'` event | signal | Fires once, synchronously, when aborted. |
| `AbortSignal.abort(reason?)` | static | Returns a signal that is already aborted. |
| `AbortSignal.timeout(ms)` | static | Returns a signal that aborts with a `TimeoutError` after `ms`. |
| `AbortSignal.any(signals)` | static | Returns a signal that aborts when any input aborts. |
AbortSignal.abort() is useful for testing. It gives you an already-aborted signal without creating a controller:
const signal = AbortSignal.abort();
console.log(signal.aborted); // true
console.log(signal.reason.name); // "AbortError"Exercises
Exercise
You call controller.abort() and then, on the next line, add an 'abort' event listener to controller.signal. Does the listener run? How should code that receives a signal late handle this case?
Show answer
No. The abort event fires once, synchronously, inside abort(), so a listener added afterward never runs. Code that may receive a signal that is already aborted must check signal.aborted (or call signal.throwIfAborted()) before relying on the event. A later chapter, "Failing Fast When the Signal Is Already Aborted", covers this pattern.
Exercise
A search box creates one AbortController at page load and calls controller.abort() whenever the user types, so that the previous fetch is cancelled. After the first keystroke, every search fails immediately with AbortError. Why, and what is the fix?
Show answer
An aborted signal stays aborted forever, and abort() cannot be undone. After the first abort, every new fetch receives a signal that is already aborted and rejects at once. The fix is to abort the previous controller and then create a new AbortController for each search, for example: previous?.abort(); previous = new AbortController(); fetch(url, { signal: previous.signal }).
Exercise
In the countTo example, what does the output look like if you change the abort delay from 350 ms to 0 ms, and why?
Show answer
It prints 1, then "stopped at 1". countTo runs synchronously up to its first await: it checks the signal, which is not aborted yet, and logs 1. The abort timer fires before the 100 ms tick resolves. At the next check the signal is aborted, so the function stops with one step completed.