Sub topic 8
Cleaning Up After Abort and After Success
This chapter assumes you have read the earlier chapters on the abort event and the cancellable delay() function. You should also be comfortable with closures and promises.
A cancellable function can finish in one of two ways. Either the work completes, or the signal aborts it. Each path leaves something behind that the other path set up, and the function has to remove it.
What leaks, and when
| Finish path | Left behind if you skip cleanup | Consequence |
|---|---|---|
| Work completes | The `abort` listener on the signal | The listener and its closure stay alive as long as the signal does |
| Signal aborts | The pending timer, socket, or child task | Work keeps running after the caller has stopped caring |
The success path is the one people forget. { once: true } removes a listener only after it fires. If the abort never happens, the listener stays. That matters when one long-lived signal is shared across many calls, such as a signal tied to a page or a server request. Every completed call adds another listener that never goes away.
One cleanup function for both paths
Put all teardown in a single cleanup function and call it from both branches. Then neither branch can forget a step, and a future change only needs editing in one place.
function delay(ms, { signal } = {}) {
return new Promise((resolve, reject) => {
if (signal?.aborted) {
reject(signal.reason);
return;
}
let timerId;
const cleanup = () => {
clearTimeout(timerId);
signal?.removeEventListener('abort', onAbort);
};
const onAbort = () => {
cleanup();
reject(signal.reason);
};
timerId = setTimeout(() => {
cleanup();
resolve();
}, ms);
signal?.addEventListener('abort', onAbort, { once: true });
});
}clearTimeout on a timer that has already fired does nothing, and so does removeEventListener for a listener that is already gone. That is why it is safe to call cleanup() from either branch.
Verifying there is no leak
In Node.js, getEventListeners from node:events shows how many listeners a signal still holds. Save this as check.mjs together with the delay function above and run it with node check.mjs:
import { getEventListeners } from 'node:events';
// paste the delay() function from above here
const controller = new AbortController();
for (let i = 0; i < 100; i++) {
await delay(1, { signal: controller.signal });
}
console.log(getEventListeners(controller.signal, 'abort').length); // 0If you remove the removeEventListener line, the output becomes 100. Node also prints a MaxListenersExceededWarning once more than 10 listeners build up on the signal.
Common mistakes
- You rely on
{ once: true }alone. It covers the abort path only. - You clear the timer only inside
onAbort. The listener still leaks on success. - You call
resolve()orreject()before cleanup and then throw inside cleanup. Clean up first, then settle the promise. - You forget resources other than timers. Close sockets, cancel animation frames, and stop intervals in the same
cleanup.
Exercise
A function opens a setInterval that polls every 100 ms and resolves when a condition becomes true. It accepts a signal. List everything its cleanup function must do, and say which paths must call it.
Show answer
Cleanup must call clearInterval on the interval ID and call signal.removeEventListener('abort', onAbort) with the same handler reference that was added. Both the success path (the condition becomes true, just before resolve) and the abort path (inside onAbort, just before reject(signal.reason)) must call it. If the polling can also fail, the error path must call it too.