Syntax
const controller = new AbortController();
operation({ signal: controller.signal });
controller.abort();Examples
Cooperative Cancellation with AbortController: working example
Run this standalone example in a modern browser console unless another environment is specified. Expected result: The console prints 1 true.
const controller = new AbortController();
const target = new EventTarget();
let calls = 0;
target.addEventListener("work", () => calls++, { signal: controller.signal });
target.dispatchEvent(new Event("work"));
controller.abort();
target.dispatchEvent(new Event("work"));
console.log(calls, controller.signal.aborted);- Expected result: The console prints 1 true.
- Aborting automatically removes the registered listener, so the second event does not increment calls.
- The controller owns cancellation; consumers receive its signal.
Best practices
- Create a fresh controller for a fresh operation.
- Distinguish expected cancellation from operational failures when reporting errors.
Runtime & versions
Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
ECMAScript specification