Timers as promises in JavaScript
node:timers/promises gives awaitable delays and intervals.
import { setTimeout as delay } from "node:timers/promises";
import { setInterval as every } from "node:timers/promises";
const started = Date.now();
await delay(10);
console.log("waited:", Date.now() - started >= 9);
console.log(await delay(1, "with a value"));
let ticks = 0;
for await (const tick of every(2)) {
ticks += 1;
if (ticks === 3) break;
}
console.log("ticks:", ticks);
const controller = new AbortController();
setTimeout(() => controller.abort(), 5);
try {
await delay(100, null, { signal: controller.signal });
} catch (error) {
console.log("canceled:", error.name);
}
How it works
setTimeoutfrom that module returns a promise.- It takes an AbortSignal, so a delay is cancellable.
setIntervalthere is an async iterable.
Keywords and builtins used here
Dateasawaitbreakcatchconstforfromifimportletoftry
The run, in numbers
- Lines
- 23
- Characters to type
- 587
- Tokens
- 160
- Three-star pace
- 105 tpm
At the three-star pace of 105 tokens a minute, this run takes about 91 seconds.
Step 2 of 2 in Events & timers, step 11 of 18 in Node.js.