Skip to main content
JavaScript & the browser·Module C9 · Lesson 7
TaskImplement wait(ms, signal) returning a Promise. setTimeout resolves; signal.abort triggers reject with AbortError. Create ctrl, schedule ctrl.abort() in 30ms, try await wait(200, ctrl.signal) in try/catch, log err.name.

AbortController as a cancellation token

125 XP9 min
Theory

Not just for fetch

C4 used AbortController to cancel a fetch. The same API is a generic cancellation token — any function that accepts a signal can be cancelled.

function wait(ms, signal) {
  return new Promise((resolve, reject) => {
    const id = setTimeout(resolve, ms);
    signal?.addEventListener("abort", () => {
      clearTimeout(id);
      reject(new DOMException("aborted", "AbortError"));
    });
  });
}

const ctrl = new AbortController();
setTimeout(() => ctrl.abort(), 50);

try {
  await wait(500, ctrl.signal);
} catch (err) {
  console.log(err.name); // "AbortError"
}

The contract

  • Accept signal as an option.
  • If signal is already aborted on entry, reject immediately.
  • Subscribe to abort and reject + clean up resources.
  • Throw an AbortError (DOMException with name "AbortError").

Why a standard

Any library that adopts this can be cancelled with the same controller as your fetch. One controller can abort multiple operations at once — pass the same signal to fetch, wait, db query, anything.

🔒

Sign up to start coding

Theory is open to everyone. The interactive editor, live preview, and check are unlocked with a 7-day free trial — card required, cancel anytime.

Sign up — free trial →

First 15 lessons in each track are free. No card needed for those.

PreviousNext lesson →

Get one Python or web tip a day — by email

Short, hand-written, no spam. Unsubscribe in one click.