typestar

AbortController in JavaScript

One signal cancels whatever is listening, including a timer.

function delay(ms, signal) {
  return new Promise((resolve, reject) => {
    const timer = setTimeout(resolve, ms);
    signal?.addEventListener("abort", () => {
      clearTimeout(timer);
      reject(signal.reason);
    }, { once: true });
  });
}

async function main() {
  const controller = new AbortController();
  setTimeout(() => controller.abort(new Error("changed my mind")), 5);

  try {
    await delay(50, controller.signal);
  } catch (error) {
    console.log("canceled:", error.message);
  }

  try {
    await delay(50, AbortSignal.timeout(5));
  } catch (error) {
    console.log("timed out:", error.name);
  }
}

main();

How it works

  1. controller.abort() fires the signal's abort event.
  2. signal.throwIfAborted is the check inside a loop.
  3. AbortSignal.timeout builds a self-canceling signal.

Keywords and builtins used here

The run, in numbers

Lines
28
Characters to type
579
Tokens
166
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 91 seconds.

Type this snippet

Step 1 of 4 in Canceling & limiting, step 15 of 19 in Promises & async.

← Previous Next →