AbortController and timeouts

A promise cannot be cancelled: once it is made, the work behind it runs to its end. What a program can do is tell the work to stop, and the language has one shared way to say it: an AbortSignal, created by an AbortController and passed, like any other value, to the code that waits.

The lesson shows the controller and its one-time event, a timer that is cleared when the signal fires, a loop that checks the signal between steps, and AbortSignal.timeout, which is a deadline built from the same object. Every program ends by itself, and none of them prints a duration.

AbortController and its signal

A controller has one method and one property: abort() and signal. The signal says whether the abort has happened and carries the reason, and it fires an abort event once, which is what the waiting code listens for.

The file controller.mjs:

const controller = new AbortController(); const { signal } = controller; console.log('before the abort:', signal.aborted); signal.addEventListener('abort', () => { console.log('the listener ran, and the reason is:', signal.reason.name); }); controller.abort(); console.log('after the abort:', signal.aborted);

node controller.mjs

before the abort: false
the listener ran, and the reason is: AbortError
after the abort: true

The listener ran inside the call to abort, before the next line, and the reason was the default one: a DOMException whose name is AbortError. Passing a value to abort(value) replaces that reason, which is how a program makes a timeout and a user cancel look different at the catch.

Aborting a timer

A promise that waits with a timer has to do two things when the signal fires: clear the timer, so the callback never runs, and reject with the reason. The function below does both, and the program aborts it from a second timer, which is the smallest useful cancellation.

The file timer.mjs:

function sleep(ms, signal) { return new Promise((resolve, reject) => { if (signal.aborted) { reject(signal.reason); return; } const timer = setTimeout(() => { resolve('the timer finished'); }, ms); signal.addEventListener( 'abort', () => { clearTimeout(timer); reject(signal.reason); }, { once: true }, ); }); } const controller = new AbortController(); setTimeout(() => { controller.abort(); }, 10); console.log('the wait starts'); try { console.log(await sleep(50, controller.signal)); } catch (error) { console.log('the wait was cancelled:', error.name); }

node timer.mjs

the wait starts
the wait was cancelled: AbortError

The fifty millisecond timer never fired, because the listener cleared it, and the promise rejected at the moment of the abort. The check at the top covers the other order, a signal that was already aborted before the call: without it the function would wait for a timer whose work nobody wants.

Aborting a task

A loop that does several steps has no single timer to clear, so it checks the signal between the steps. What is already done stays done, and the throw stops the rest: that is the contract of an abort, which is a request rather than a rollback.

The file task.mjs:

const delay = (value, ms) => new Promise((resolve) => { setTimeout(() => resolve(value), ms); }); async function copy(names, signal) { const done = []; for (const name of names) { if (signal.aborted) { throw signal.reason; } done.push(await delay(name, 40)); console.log('copied', name); } return done; } const controller = new AbortController(); setTimeout(() => { controller.abort(); }, 10); try { const done = await copy(['a', 'b', 'c'], controller.signal); console.log('copied:', done.join(',')); } catch (error) { console.log('the copy stopped:', error.name); }

node task.mjs

copied a
the copy stopped: AbortError

The first name was copied and the second step never started, because the check at the top of the iteration saw the abort. The message says stopped rather than failed for that reason: an abort is a decision of the caller, and a program often treats it as a normal ending.

AbortSignal.timeout

AbortSignal.timeout(ms) builds a signal that aborts itself after the delay, with a reason named TimeoutError. The program below races a slow call against that signal, so a deadline is written as a promise and the catch can tell a timeout from a cancellation.

The file timeout.mjs:

const delay = (value, ms) => new Promise((resolve) => { setTimeout(() => resolve(value), ms); }); const signal = AbortSignal.timeout(10); try { const value = await Promise.race([ delay('the slow answer', 50), new Promise((resolve, reject) => { signal.addEventListener('abort', () => reject(signal.reason), { once: true }); }), ]); console.log(value); } catch (error) { console.log('the wait timed out:', error.name); }

node timeout.mjs

the wait timed out: TimeoutError

The slow call lost the race, and the name of the reason says which side won: TimeoutError for a deadline and AbortError for a cancel. That difference is what a program needs to decide whether to retry, to report a slow service, or to stop quietly. One detail of the deadline: its timer does not keep the process alive, so a program that awaits nothing else ends before it fires, and the slow call in this one is what holds the loop. The next lesson puts the same signal to work in a queue that runs a limited number of jobs at once.

Exercises

  1. Pass a message to abort and print the reason. Which name does it have then?
  2. Abort the wait of the second program before it starts, by calling controller.abort() on the line before the try. Which branch runs?
  3. Give the copy task a smaller delay and check how many names are copied before it stops.
  4. Make the timeout program print the value when the slow call wins, using a delay of five milliseconds and a timeout of a hundred.
  5. Count the aborts in a program that aborts three times. How many listener calls does one listener get?

Questions

A new set of questions in a new order every time. Choose one answer for each, then check.

  1. What is an AbortSignal?

    Answer

    An object that reports whether the work has been told to stop

    The signal carries the state and the event, and the code that waits listens to it.

  2. What does controller.abort() do?

    Answer

    It sets aborted to true and fires the abort event once

    The signal changes state once and notifies its listeners.

  3. What is the reason of a plain abort()?

    Answer

    A DOMException named AbortError

    The default reason is a DOMException, and its name is AbortError.

  4. What must a promise built on a timer do when the signal aborts?

    Answer

    Clear the timer and reject with the reason

    The timer has to stop or the callback would run later, and the promise has to settle now.

  5. What does this program print? const controller = new AbortController(); console.log(controller.signal.aborted); controller.abort(); console.log(controller.signal.aborted);

    Answer

    false / true

    The signal starts unset and the abort changes it once.

  6. What does this program print? const controller = new AbortController(); controller.signal.addEventListener("abort", () => console.log("stopped")); controller.abort(); controller.abort();

    Answer

    stopped

    The abort fires once, and the second call changes nothing.

  7. What does this program print? const controller = new AbortController(); setTimeout(() => controller.abort(), 10); try { await new Promise((resolve, reject) => { controller.signal.addEventListener("abort", () => reject(controller.signal.reason), { once: true }); }); } catch (error) { console.log(error.name); }

    Answer

    AbortError

    A timer calls abort with no argument, so the reason is the default DOMException named AbortError.

  8. Why pass { once: true } to the abort listener?

    Answer

    The event fires once, so the listener has no second use

    The listener removes itself, which keeps the signal from holding it after the abort.

  9. What happens to the steps already done when a task is aborted?

    Answer

    They stay, and the abort only stops the next step

    An abort is a request to stop, not a rollback, so the caller decides what to do with the work done.

  10. Which call starts the abort?

    Answer

    controller.abort()

    The controller owns the method, and the signal only reports the state.

The code on this page was run with Node.js 24.22.1 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.

Article author: Arthur Isaev