Late abort Listeners Never Fire
Adding an abort listener after the signal already aborted does not throw and does not fire, so cleanup paths must check signal.aborted before subscribing.
Code
const controller = new AbortController();
controller.abort(new Error('too late'));
const signal = controller.signal;
console.log('aborted:', signal.aborted);
let fired = false;
// 已中止的信号上再挂监听:不抛错、也不触发,安静地什么都不做
signal.addEventListener('abort', () => { fired = true; });
await Promise.resolve();
await new Promise((resolve) => setTimeout(resolve, 0));
console.log('late listener fired:', fired);
// 想保证清理逻辑跑一次,先查 aborted 再决定是订阅还是直接执行
if (signal.aborted) {
console.log('cleanup runs inline:', signal.reason.message);
} else {
signal.addEventListener('abort', () => console.log('cleanup via event'), { once: true });
}Output
Captured from a sandboxed run of this snippet in the build pipeline.
aborted: true
late listener fired: false
cleanup runs inline: too lateTracing each move
Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed.
Demo state sits in top-level bindings: controller, signal, fired.
Watch out for
- The dependency roster is blank; the language runtime supplies the lot.
Applying it
Output lines are prefixed (aborted:, late listener fired:, cleanup runs inline:), letting every printed line be tied back to the step that made it.
Statements that matter
await new Promise((resolve) => setTimeout(resolve, 0));
signal.addEventListener('abort', () => { fired = true; });
await Promise.resolve();
Interactive Tools for This Topic
DOM Event Propagation VisualizerVisualize DOM event capturing, targeting, and bubbling phases in real time. Toggle stopPropagation and stopImmediatePropagation to see how events traverse the tree.HTTP Retry & Backoff CalculatorSimulate exponential backoff retry schedules with Full, Equal, Decorrelated, or No Jitter to inspect per-attempt wait times and cumulative latency.
FAQ
- Is a package install part of the setup?
- No. Installation is unnecessary because only built-in APIs are used. Its state lives in module-level bindings: `controller`, `signal`, `fired`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.