Sub topic 7
Building a Cancellable Promise: A Cancellable delay()
This chapter assumes you know how to construct a promise with new Promise((resolve, reject) => ...), how setTimeout and clearTimeout work, and the basics of AbortSignal from earlier chapters: signal.aborted, signal.reason, the abort event, and the convention of accepting { signal } in an options object.
So far you have seen the parts on their own. Here you put them together into a function that wraps timer-based work in a promise, resolves when the work finishes, and rejects at the moment the caller aborts. The example is delay(ms, { signal }), a promise-based sleep. It is small, but it uses the same structure you need to wrap any callback- or event-based API.
What the Function Must Do
A cancellable delay() has four jobs:
| Situation | Required behavior |
|---|---|
| Called with a signal that is already aborted | Reject immediately with `signal.reason`, and start no timer |
| The timer fires before any abort | Resolve, and stop listening for `abort` |
| The signal aborts while the timer is pending | Clear the timer, and reject with `signal.reason` |
| Called with no signal | Behave like a plain promise-based sleep |
The last row matters. Cancellation should be optional, so every use of signal has to tolerate undefined.
The Implementation
function delay(ms, { signal } = {}) {
return new Promise((resolve, reject) => {
if (signal?.aborted) {
reject(signal.reason);
return;
}
const onAbort = () => {
clearTimeout(timerId);
reject(signal.reason);
};
const timerId = setTimeout(() => {
signal?.removeEventListener('abort', onAbort);
resolve();
}, ms);
signal?.addEventListener('abort', onAbort, { once: true });
});
}Each part of the executor is there for a specific reason.
Step 1: Fail fast
The signal?.aborted check comes first. An abort event fires only once, at the moment of abort. If the signal was aborted before delay() was called, a listener added now would never run and the promise would wait out the full ms. The early return also keeps the executor from starting a timer that nobody wants.
Step 2: Define the abort handler
onAbort does two things, in this order:
- It calls
clearTimeout(timerId), so the pending timer callback never runs and the timer stops holding the event loop open. In Node.js, an uncleared five-second timer keeps the process alive for five seconds even after the promise has rejected. - It calls
reject(signal.reason), so the caller gets whatever reason the signal carries. That is aDOMExceptionnamed"AbortError"by default, a"TimeoutError"forAbortSignal.timeout(), or a custom value passed toabort(reason).
Rejecting with signal.reason instead of building a new error makes your function behave like the platform APIs. fetch() and node:timers/promises both reject with the signal's reason, so callers can handle your function and theirs with the same catch logic.
Step 3: Start the work
setTimeout starts the actual work. When it fires, the callback removes the abort listener before it resolves. Without that removal, a long-lived signal (one shared across many calls, for example) would collect one dead listener per completed delay. The next chapter covers cleanup in detail. For now, note that the success path has to clean up as well as the abort path.
Step 4: Subscribe to abort
The listener is added last, with { once: true } so it removes itself after it runs. Both settlement paths end with no listener attached:
- On success, the timer callback removes the listener explicitly.
- On abort,
once: trueremoves it automatically.
Why the Order Is Safe
onAbort refers to timerId, which is declared with const after onAbort. That looks like a temporal dead zone bug, but it is not one. The closure only reads timerId when it runs, and it can only run after addEventListener has attached it, which happens after timerId is initialized.
The order would become fragile if you attached the listener before creating the timer and something between those two lines could abort the signal synchronously. Calling controller.abort() dispatches the abort event synchronously, so onAbort would run while timerId was still in its dead zone and would throw a ReferenceError. Follow the rule: create the resource first, then subscribe.
Races Between the Timer and the Abort
JavaScript runs one callback at a time, so the timer callback and the abort listener can never interleave. Whichever runs first wins:
- If the timer runs first, it removes the listener and resolves. A later
abort()finds no listener, and the promise stays fulfilled. - If the abort runs first,
clearTimeoutcancels the queued timer callback, soresolve()never runs.
Even without the cleanup, a promise settles only once. A late resolve() after reject() is ignored. You still need the cleanup to release the resources, even though correctness of the result does not depend on it.
Calling It
const controller = new AbortController();
const started = Date.now();
delay(5000, { signal: controller.signal })
.then(() => console.log('finished'))
.catch((err) => {
if (err.name === 'AbortError') {
console.log(`cancelled by the caller after ${Date.now() - started} ms`);
} else {
throw err;
}
});
setTimeout(() => controller.abort(), 1000);Run this in Node.js 17.3 or later, or in a browser console, with delay defined above it. It prints a message after about 1000 ms and the process exits right away, because the five-second timer was cleared. Delete the clearTimeout line and run it again: the message still appears at 1000 ms, but Node waits another four seconds before it exits.
The err.name check is important. Only cancellation is swallowed, and every other error is rethrown. A later chapter covers caller-side handling in more depth.
The Same Pattern for Any Callback API
delay() is a template. Any work that starts with one call and finishes through a callback or event fits the same structure:
- Return a new promise.
- If the signal is already aborted, reject with
signal.reasonand return. - Start the work and keep a handle to it.
- On completion, detach the abort listener, then resolve or reject.
- On abort, release the handle, then reject with
signal.reason.
Here it is applied to waiting for a one-time event on an EventTarget:
function waitForEvent(target, type, { signal } = {}) {
return new Promise((resolve, reject) => {
if (signal?.aborted) {
reject(signal.reason);
return;
}
const onEvent = (event) => {
signal?.removeEventListener('abort', onAbort);
resolve(event);
};
const onAbort = () => {
target.removeEventListener(type, onEvent);
reject(signal.reason);
};
target.addEventListener(type, onEvent, { once: true });
signal?.addEventListener('abort', onAbort, { once: true });
});
}
const target = new EventTarget();
const controller = new AbortController();
waitForEvent(target, 'ready', { signal: controller.signal })
.then((e) => console.log('got', e.type))
.catch((err) => console.log('stopped:', err.name));
controller.abort(); // prints "stopped: AbortError"Here the "handle" is the event listener on target, and "releasing" it means removing that listener.
Common Mistakes
| Mistake | Symptom |
|---|---|
| No `signal.aborted` check | A pre-aborted call waits the full duration, then resolves |
| Rejecting with `new Error('aborted')` | Callers checking `err.name === 'AbortError'` or `'TimeoutError'` miss it |
| Not calling `clearTimeout` on abort | Promise rejects, but the timer keeps the process alive |
| Not removing the listener on success | Shared signals pile up listeners. Node warns after 10 |
| Using `signal.addEventListener` without `?.` | `TypeError` when the caller passes no signal |
| Listener attached before the resource exists | `ReferenceError` if the signal aborts synchronously during setup |
Exercise
A caller awaits delay(100, { signal }) to completion, then calls controller.abort() a second later. What happens to the promise, and does onAbort run?
Show answer
The promise stays fulfilled. The timer callback already removed onAbort with removeEventListener, so nothing runs on abort, and a settled promise cannot change state anyway.
Exercise
Rewrite delay so it resolves with a value: delay(ms, value, { signal }) should resolve to value. Which single line changes besides the signature?
Show answer
In the timer callback, change resolve() to resolve(value). The signature becomes function delay(ms, value, { signal } = {}), and all of the cancellation logic stays the same.
Exercise
Why does onAbort call clearTimeout before reject, and would swapping the two lines change behavior?
Show answer
Swapping them changes nothing visible. reject does not run callbacks synchronously (promise reactions are queued as microtasks), so the timer is cleared either way before anything else runs. Clearing first simply makes it clear that the resource is released before the result is reported.
Exercise
In waitForEvent, what goes wrong if onAbort does not remove the onEvent listener from target?
Show answer
The promise still rejects correctly, but target keeps a reference to onEvent (and through it the promise's resolve function) until the event fires, if it ever does. That leaks memory, and the listener runs pointlessly later.