Codectionary / Developer documentation / JavaScript

Cooperative Cancellation with AbortController

AbortController exposes a signal that compatible operations can observe. Calling abort marks the signal aborted and notifies listeners; it does not forcibly stop arbitrary JavaScript. APIs such as fetch and event listener registration can cooperate with the signal. An aborted signal cannot be reset.

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);
  1. Expected result: The console prints 1 true.
  2. Aborting automatically removes the registered listener, so the second event does not increment calls.
  3. 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

Specifications & further reading