Sub topic 8
Cleaning Up After Abort and After Success
A cancellable function can finish in three ways. It can complete normally, it can fail with an error, or the caller can abort it. On every one of these paths it has to release what it set up. If it doesn't, the function still returns the right result, but each call leaves something behind: an abort listener, a timer, or an interval. Over many calls those leftovers turn into a memory leak or into side effects that fire later.
This chapter assumes you have read the previous chapter's cancellable delay(). It also assumes you know closures, addEventListener/removeEventListener, and how a promise settles only once.
What Leaks, and Why It Matters
Look at the work a cancellable promise sets up:
- The work resource: a
setTimeoutorsetIntervalid, a socket, a worker, a subscription. - The abort listener: a function registered on the caller's signal.
Each needs its own cleanup, and the cleanup depends on which path ended the work.
| How the work ends | Work resource | Abort listener |
|---|---|---|
| Completes normally | Usually already finished (timer fired), but intervals and subscriptions still need stopping | Must be removed by hand |
| Fails with an error | Must be stopped | Must be removed by hand |
| Caller aborts | Must be stopped (`clearTimeout`, `close()`, …) | Removed automatically if added with `{ once: true }` |
The abort listener is the one people forget. Signals often live much longer than a single call. A page-level controller might cancel everything when the user navigates away, and a request-scoped signal might be passed to dozens of helpers. Every listener you add to that signal stays reachable until the signal is collected. The closure stays reachable too, along with everything it captured, such as resolve, reject, timer ids, and maybe large buffers.
Seeing the Leak
The following Node.js script (save it as leak.mjs so top-level await works) runs a delay that forgets to remove its listener, then counts the listeners left on the signal. getEventListeners from node:events works on any EventTarget, including AbortSignal.
import { getEventListeners } from 'node:events';
function leakyDelay(ms, { signal } = {}) {
return new Promise((resolve, reject) => {
if (signal?.aborted) {
reject(signal.reason);
return;
}
const timerId = setTimeout(resolve, ms);
signal?.addEventListener('abort', () => {
clearTimeout(timerId);
reject(signal.reason);
}, { once: true });
});
}
function cleanDelay(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 });
});
}
const leaky = new AbortController();
for (let i = 0; i < 50; i++) {
await leakyDelay(1, { signal: leaky.signal });
}
console.log('leaky:', getEventListeners(leaky.signal, 'abort').length); // 50
const clean = new AbortController();
for (let i = 0; i < 50; i++) {
await cleanDelay(1, { signal: clean.signal });
}
console.log('clean:', getEventListeners(clean.signal, 'abort').length); // 0Node may also print a MaxListenersExceededWarning for the leaky version once more than ten listeners pile up on one signal. That warning is often the first sign of this bug in production logs.
Why removeEventListener Sometimes Does Nothing
removeEventListener removes a listener only if you pass the same function object and the same capture setting you used when adding it. The following mistakes fail silently:
- Registering an inline arrow function. You have no reference to pass back later.
- Passing a new arrow with the same body to
removeEventListener. It is a different object. - Adding with
{ capture: true }and removing without it. Capture doesn't matter forAbortSignalin practice, but the matching rule still applies.
Store the handler in a variable, as cleanDelay does with onAbort.
Cleaning Up on Every Path
cleanDelay works because a timer has only one success path. Real work often has several: a result arrives, an error arrives, or a callback reports a failure. Writing cleanup separately in each branch makes it easy to miss one. A better pattern routes every outcome through a single finish function that runs at most once.
flowchart TD
A[Start work] --> B[Add abort listener]
B --> C[Start timer / interval / resource]
C --> D{Which happens first?}
D -->|Work completes| E[finish with resolve]
D -->|Work fails| F[finish with reject error]
D -->|Signal aborts| G[finish with reject signal.reason]
E --> H[Already settled?]
F --> H
G --> H
H -->|Yes| I[Ignore]
H -->|No| J[Mark settled, remove listener, stop resource, settle promise]The following helper captures that flow. You pass it a setup function that starts the work and returns a teardown function.
function cancellable(signal, setup) {
return new Promise((resolve, reject) => {
if (signal?.aborted) {
reject(signal.reason);
return;
}
let settled = false;
let teardown = () => {};
const finish = (settle, value) => {
if (settled) return;
settled = true;
signal?.removeEventListener('abort', onAbort);
teardown();
settle(value);
};
const onAbort = () => finish(reject, signal.reason);
signal?.addEventListener('abort', onAbort, { once: true });
try {
const result = setup(
(value) => finish(resolve, value),
(err) => finish(reject, err),
);
if (typeof result === 'function') {
if (settled) result();
else teardown = result;
}
} catch (err) {
finish(reject, err);
}
});
}A few details in this helper are deliberate:
- The
settledflag. A promise ignores a secondresolveorreject, but your cleanup code would still run twice. Some teardown functions are not safe to repeat, such as closing a connection pool you share with other code. - Removing the listener inside
finish. This covers all paths at once. On the abort path,once: truehas already removed it, and removing an absent listener is a harmless no-op. setupthat settles synchronously. Ifsetupcallsresolvebefore it returns,finishruns whileteardownis still the empty placeholder. Theif (settled) result()line runs the real teardown afterward, so nothing is left running.setupthat throws. Without thetry/catch, the promise constructor would reject for you, but the abort listener would stay attached. Routing the error throughfinishremoves the listener.
Using the Helper with an Interval
Intervals show why the success path also needs teardown. A timer stops on its own after it fires, but an interval keeps running until you clear it. Here is a polling function that waits for a condition:
function waitFor(check, { intervalMs = 100, signal } = {}) {
return cancellable(signal, (resolve, reject) => {
const id = setInterval(() => {
try {
if (check()) resolve();
} catch (err) {
reject(err);
}
}, intervalMs);
return () => clearInterval(id);
});
}
let ready = false;
setTimeout(() => { ready = true; }, 350);
const controller = new AbortController();
await waitFor(() => ready, { signal: controller.signal });
console.log('condition met; interval cleared, listener removed');All three outcomes clear the interval: the condition becomes true, check throws, or the caller aborts. If teardown ran only on abort, a successful waitFor would keep calling check every 100 ms for as long as the process runs.
The same delay from the previous chapter, written with the helper, becomes very short:
function delay(ms, { signal } = {}) {
return cancellable(signal, (resolve) => {
const id = setTimeout(resolve, ms);
return () => clearTimeout(id);
});
}Calling clearTimeout on a timer that has already fired does nothing, so running teardown on the success path is safe.
Edge Cases
Abort Arrives After Success
A caller might abort a long-lived signal minutes after your function resolved. If you removed the listener, nothing happens, which is correct. If you didn't, the leftover handler runs. With a timer that is mostly harmless: reject on a settled promise is ignored and clearTimeout on a finished timer does nothing. With other resources it can cause damage. A handler that calls socket.destroy() could close a connection that has since been returned to a pool and handed to someone else.
Cleanup Must Not Throw
If teardown throws inside finish, the promise never settles, because settle(value) comes after it. Teardown functions should be simple and safe to call. If one can fail, wrap it in a try/catch and settle the promise anyway.
Cleanup That Is Itself Asynchronous
Some resources close asynchronously, for example await file.close(). Settle the promise first so the caller isn't kept waiting on cleanup after an abort, then run the async teardown and handle its errors separately (log them, for example). Don't let a failed close replace the abort reason the caller expects.
Exercise
A function adds its abort listener with { once: true } and calls clearTimeout inside it, but never calls removeEventListener. A single page-level signal is passed to this function 1,000 times, and every call completes normally. How many abort listeners are attached to the signal afterward, and why?
Show answer
1,000. { once: true } removes a listener only when the abort event fires. Every call completed without an abort, so no listener ran and none was removed. The function must call removeEventListener('abort', handler) on the success path, using the same handler reference.
Exercise
In the cancellable helper, what goes wrong if you delete the settled flag and the if (settled) return; guard?
Show answer
finish could run more than once, for example when the work calls resolve and the signal later aborts in the same tick, or when a callback fires twice. The promise would ignore the second settlement, but teardown and removeEventListener would run again. Teardown code that is not safe to repeat, such as closing a shared resource or decrementing a counter, would then misbehave.
Exercise
Rewrite this function so the interval is cleared and the listener removed on every path: function tick(n, { signal } = {}) { return new Promise((resolve) => { let i = 0; const id = setInterval(() => { if (++i === n) resolve(); }, 10); signal?.addEventListener('abort', () => clearInterval(id)); }); }
Show answer
Use the helper: function tick(n, { signal } = {}) { return cancellable(signal, (resolve) => { let i = 0; const id = setInterval(() => { if (++i === n) resolve(); }, 10); return () => clearInterval(id); }); }. The original never clears the interval on success, never removes its listener, and never rejects on abort, so the caller would wait forever. The helper fixes all three problems and also rejects at once if the signal is already aborted.