AbortController Cancels Polling Loops
A poll loop that checks an AbortSignal between attempts exits promptly when the caller aborts, instead of sleeping through every remaining interval.
Code
// cancellable polling: every attempt checks the AbortSignal first, so abort exits immediately instead of sleeping through the interval
const sleep = (ms, signal) =>
new Promise((resolve, reject) => {
if (signal?.aborted) return reject(signal.reason);
const timer = setTimeout(resolve, ms);
signal?.addEventListener('abort', () => {
clearTimeout(timer);
reject(signal.reason);
}, { once: true });
});
async function pollUntil(check, { intervalMs = 25, maxAttempts = 8, signal } = {}) {
for (let attempt = 1; attempt <= maxAttempts; attempt++) {
signal?.throwIfAborted(); // throws signal.reason once cancelled
if (check(attempt)) return attempt;
await sleep(intervalMs, signal);
}
throw new Error('condition not met after ' + maxAttempts + ' attempts');
}
async function main() {
const metAt = await pollUntil((n) => n >= 3, { intervalMs: 15 });
console.log('condition met on attempt:', metAt);
const controller = new AbortController();
setTimeout(() => controller.abort(new Error('caller gave up')), 40);
try {
await pollUntil(() => false, { intervalMs: 200, signal: controller.signal });
} catch (err) {
console.log('aborted early:', err.message);
}
}
main();How it works
AbortController Cancels Polling Loops keeps everything in the functions sleep, pollUntil and main.
Repetition is confined to for (let attempt = 1; attempt <= maxAttempts; attempt++) — the rest of the file is straight-line. The asynchronous flow is linearized with await, keeping failure handling local. Error marks loop exhaustion — the code reaches it only after the final attempt fails to return early. Cancellation is a separate path: throwIfAborted throws signal.reason the moment the caller aborts, and the sleep helper rejects with it mid-wait.
What to watch for
- The guard
signal?.abortedshort-circuits the flow with an earlyreturnwhen its condition holds.
Using it
The entry-point signature is const sleep = (ms, signal)
The demo output is labeled (condition met on attempt:, aborted early:); each label names the call that printed it.
main sequences pollUntil; executing the file runs that flow once.
Key statements
signal?.addEventListener('abort', () => {
clearTimeout(timer);
reject(signal.reason);
}, { once: true });
await pollUntil(() => false, { intervalMs: 200, signal: controller.signal });
const metAt = await pollUntil((n) => n >= 3, { intervalMs: 15 });
Interactive Tools for This Topic
FAQ
- What makes the code give up?
- Only when the loop gives up — `Error` fires once the final attempt has been tried and no early return happened. Aborting the signal is a separate path: `throwIfAborted` raises `signal.reason` immediately, and the sleep helper rejects with it mid-wait.
- What does AbortController Cancels Polling Loops print when run?
- The script runs standalone; its 2 labeled outputs include `condition met on attempt:`, `aborted early:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.