timers/promises setInterval With AbortSignal

Drive periodic work with timers/promises setInterval as an async iterable and cancel it mid-loop by aborting the signal passed in options.

JavascriptResilience

Code

javascriptsnippet
16 lines
import { setInterval as every } from 'node:timers/promises';

// every() yields an async iterable: await one tick per loop pass
const ac = new AbortController();
let ticks = 0;

try {
  for await (const stamp of every(50, 'tick', { signal: ac.signal })) {
    ticks += 1;
    console.log(stamp, ticks);
    if (ticks === 3) ac.abort(); // cancellation ends the loop
  }
} catch (err) {
  console.log('aborted:', err.name === 'AbortError');
}
console.log('final ticks:', ticks);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

tick 1
tick 2
tick 3
aborted: true
final ticks: 3

What the code does

Iteration happens inside for await (const stamp of every(50, 'tick', { signal: ac.signal })) — everything outside it runs once. Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. node:timers/promises supplies setInterval — built-in surface, no package involved.

Top-level bindings ac, ticks hold the demo state — nothing sits inside a function scope.

Watch out for

  • The dependency surface is just node:timers/promises, and that one is built into Node.js.

Applying it

The run emits 2 labeled sections — aborted:, final ticks: — one per step.

Statements that matter

for await (const stamp of every(50, 'tick', { signal: ac.signal })) {
  ticks += 1;
  console.log(stamp, ticks);
  if (ticks === 3) ac.abort(); // cancellation ends the loop
}
const ac = new AbortController();

Interactive Tools for This Topic

FAQ

Is the imported module an npm package?
No — `node:timers/promises` is built into Node.js. The `node:` prefix marks core modules, so there is nothing to add to a project.