Skip to content

AbortController & Cancellation

The Course
•
16 min study

The caller owns a cancellation signal

new AbortController() creates a controller with a signal property. Pass the signal to an operation such as fetch using { signal: controller.signal }. Calling abort asks participating work to stop. It is a request, not a magic interruption of arbitrary JavaScript. A custom operation must cooperate with the signal.

Check signal.aborted when starting, because the signal may already be cancelled. For future cancellation, listen for its abort event. Remove listeners and clear timers when settling so completed work does not retain unnecessary callbacks. A controller's signal cannot be reset; use a new controller for a new operation.

Browser fetch normally rejects with an AbortError when aborted without a custom reason. The small function below models that behavior with an Error whose name is set explicitly. Your UI should treat intentional cancellation differently from "service unavailable." Ordinary failures should remain visible.

Cancellation and correctness are related but separate. A service might ignore the signal or finish just before abort. On Day 5 we will also prevent stale results from replacing a newer search. Cancelling saves work when possible; a current-request check protects the displayed result.

Predict and trace

Write the output before running. Follow the values through each call; if your prediction differs, identify the first step that surprised you.

Predict, then run JavaScript
async function main() {
  function abortError() {
    const error = new Error("Cancelled");

    error.name = "AbortError";
    return error;
  }

  async function read(signal) {
    if (signal.aborted) {
      throw abortError();
    }

    return "Ready";
  }

  const controller = new AbortController();

  controller.abort();

  try {
    await read(controller.signal);
  } catch (error) {
    console.log(error.name);
  }

  console.log(controller.signal.aborted);
}

main();
Check your prediction
Text
AbortError
true

This example cancels before work starts. The final demo service also listens for abort while its timer is pending.

Cancel work that is already pending

The earlier async read settles immediately. Now keep a promise pending with a timer and cancel it after starting. The signal emits an abort event. The same onAbort function is registered and removed; creating a different callback would not remove the original listener. No timing guess is needed: abort happens synchronously before a timer task can run.

Cancel work that is already pending JavaScript
async function main() {
  function waitForTitle(signal) {
    return new Promise((resolve, reject) => {
      function onAbort() {
        clearTimeout(timer);
        signal.removeEventListener("abort", onAbort);

        const error = new Error("Cancelled");

        error.name = "AbortError";
        reject(error);
      }

      const timer = setTimeout(() => {
        signal.removeEventListener("abort", onAbort);
        resolve("Notes");
      }, 0);

      if (signal.aborted) {
        onAbort();
      } else {
        signal.addEventListener("abort", onAbort, { once: true });
      }
    });
  }

  const controller = new AbortController();
  const pending = waitForTitle(controller.signal);

  controller.abort();

  try {
    console.log(await pending);
  } catch (error) {
    console.log(error.name);
  }
}

main();
Check your prediction
Text
AbortError

The { once: true } listener option removes the listener after its first event. Success also removes it, and cancellation clears the timer. The timer variable is assigned before onAbort can run; declaring a function does not execute its body.

Build it yourself

Exercise

A cancellable wait that cleans up

Write wait(ms, signal): a promise that fulfills with "done" after ms milliseconds, or rejects with an AbortError if the signal is aborted, whether before the call or during the wait. Like the example above, it must leave nothing behind: the abort listener is removed and the timer cleared on every path. This time, do not rely on { once: true }; remove the listener yourself.

The test program counts the abort listeners attached to each signal and waits past the timer, so a leaked listener or a timer left running shows up as a nonzero count. It should print:

Text
abort before start: AbortError, listeners left 0
abort while waiting: AbortError, listeners left 0
no abort: done, listeners left 0
Your working space JavaScript
async function main() {
  function wait(ms, signal) {
    // Resolve with "done" after ms, or reject with an AbortError.
    // Remove the abort listener and clear the timer on every path.
    return new Promise(resolve => setTimeout(() => resolve("done"), ms));
  }

  // Test helper: count the abort listeners currently attached to a signal.
  function trackListeners(signal) {
    const counter = { active: 0 };
    const add = signal.addEventListener.bind(signal);
    const remove = signal.removeEventListener.bind(signal);
    signal.addEventListener = (type, listener, options) => {
      counter.active += 1;
      add(type, listener, options);
    };
    signal.removeEventListener = (type, listener, options) => {
      counter.active -= 1;
      remove(type, listener, options);
    };
    return counter;
  }

  async function outcome(promise) {
    try {
      return await promise;
    } catch (error) {
      return error.name;
    }
  }

  const pause = ms => new Promise(resolve => setTimeout(resolve, ms));

  const schedules = {
    "abort before start": async (controller, signal) => {
      controller.abort();
      return outcome(wait(20, signal));
    },
    "abort while waiting": async (controller, signal) => {
      const pending = wait(20, signal);
      controller.abort();
      return outcome(pending);
    },
    "no abort": async (controller, signal) => outcome(wait(20, signal))
  };

  for (const [name, run] of Object.entries(schedules)) {
    const controller = new AbortController();
    const listeners = trackListeners(controller.signal);
    const result = await run(controller, controller.signal);
    await pause(40); // past the 20 ms timer: a timer left running would show up now
    console.log(`${name}: ${result}, listeners left ${listeners.active}`);
  }
}

main();
Hint 1: the idea

There are three schedules and each one has its own exit: already aborted (never start the timer), aborted while pending (cancel the timer, drop the listener, reject), and finished normally (drop the listener, resolve). Whatever an exit did not create, it must not clean up, and whatever was created, some exit must clean up.

Hint 2: a first step

Handle the already-aborted case first: check signal.aborted at the top of the executor and reject without creating a timer or a listener. Run it: the first line becomes AbortError, listeners left 0, while "abort while waiting" still prints done.

Show one solution
JavaScript
async function main() {
  function wait(ms, signal) {
    return new Promise((resolve, reject) => {
      function abortError() {
        const error = new Error("Cancelled");
        error.name = "AbortError";
        return error;
      }

      if (signal.aborted) {
        reject(abortError());
        return;
      }

      function onAbort() {
        clearTimeout(timer);
        signal.removeEventListener("abort", onAbort);
        reject(abortError());
      }

      const timer = setTimeout(() => {
        signal.removeEventListener("abort", onAbort);
        resolve("done");
      }, ms);

      signal.addEventListener("abort", onAbort);
    });
  }

  // Test helper: count the abort listeners currently attached to a signal.
  function trackListeners(signal) {
    const counter = { active: 0 };
    const add = signal.addEventListener.bind(signal);
    const remove = signal.removeEventListener.bind(signal);
    signal.addEventListener = (type, listener, options) => {
      counter.active += 1;
      add(type, listener, options);
    };
    signal.removeEventListener = (type, listener, options) => {
      counter.active -= 1;
      remove(type, listener, options);
    };
    return counter;
  }

  async function outcome(promise) {
    try {
      return await promise;
    } catch (error) {
      return error.name;
    }
  }

  const pause = ms => new Promise(resolve => setTimeout(resolve, ms));

  const schedules = {
    "abort before start": async (controller, signal) => {
      controller.abort();
      return outcome(wait(20, signal));
    },
    "abort while waiting": async (controller, signal) => {
      const pending = wait(20, signal);
      controller.abort();
      return outcome(pending);
    },
    "no abort": async (controller, signal) => outcome(wait(20, signal))
  };

  for (const [name, run] of Object.entries(schedules)) {
    const controller = new AbortController();
    const listeners = trackListeners(controller.signal);
    const result = await run(controller, controller.signal);
    await pause(40); // past the 20 ms timer: a timer left running would show up now
    console.log(`${name}: ${result}, listeners left ${listeners.active}`);
  }
}

main();
Text
abort before start: AbortError, listeners left 0
abort while waiting: AbortError, listeners left 0
no abort: done, listeners left 0

The early return after the pre-abort rejection means that path never creates a timer or listener, so there is nothing to clean up. onAbort clears the timer and removes itself; the timer callback removes onAbort. Each path undoes exactly what was set up. Leave out clearTimeout and "abort while waiting" reports listeners left -1, because the forgotten timer fires later and removes a listener that is already gone. Leave out the removal in the timer callback and "no abort" reports listeners left 1: a finished wait still holds a callback on the caller's signal. The capstone's demo service uses this same shape.

Test a changed requirement

Call abort twice and observe that the signal stays aborted. Explain why reusing that signal for a retry would immediately reject.

Explain before moving on

Why might a current-request check still be needed after abort? Who decides that cancellation is intentional?

Going further

See MDN’s AbortSignal reference for the signal API. The exercises use explicit controllers and listeners so the ownership and cleanup are visible.

Was this article helpful?

Your response is saved on this device.