timers/promises Makes Sleep Awaitable
timers/promises turns timers into awaitable promises: sleep reads linearly, setImmediate yields one macrotask turn, and setInterval iterates ticks that abort.
Code
import { setTimeout as sleep, setInterval as every, setImmediate as yieldToLoop } from 'node:timers/promises';
// awaitable 定时器:不再手写 new Promise 包一层
const start = Date.now();
await sleep(50);
console.log('slept >=50ms:', Date.now() - start >= 50);
// setImmediate:把控制权交回事件循环之后继续执行
await yieldToLoop();
console.log('resumed after a macrotask turn');
// setInterval 返回异步可迭代对象:for await 每到一拍处理一次
const controller = new AbortController();
let ticks = 0;
let lastValue = '';
try {
for await (const value of every(40, 'tick', { signal: controller.signal })) {
ticks += 1;
lastValue = value;
if (ticks === 3) controller.abort(); // 取消走 AbortSignal 同一协议
}
} catch (error) {
console.log('interval aborted with:', error.name);
}
console.log('processed', ticks, 'ticks; last yield:', lastValue);Output
Captured from a sandboxed run of this snippet in the build pipeline.
slept >=50ms: true
resumed after a macrotask turn
interval aborted with: AbortError
processed 3 ticks; last yield: tickHow the snippet works
Iteration happens inside for await (const value of every(40, 'tick', { signal: controller.signal })) — everything outside it runs once. Asynchronous boundaries use await, so failures surface as rejected promises at the call site instead of being swallowed. The only import source is node:timers/promises, a Node.js built-in, exposing setTimeout, setInterval, setImmediate.
The file’s state is a handful of top-level bindings: start, controller, ticks, lastValue.
Points of care
node:timers/promisesresolves inside Node.js without any package — it is a core module.
Applying it
Output lines are prefixed (slept >=50ms:, resumed after a macrotask turn, interval aborted with:), making each step’s effect easy to spot.
Statements that matter
for await (const value of every(40, 'tick', { signal: controller.signal })) {
ticks += 1;
lastValue = value;
if (ticks === 3) controller.abort(); // 取消走 AbortSignal 同一协议
}
const controller = new AbortController();
await yieldToLoop();
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.
Report a problem with this exampleOpens a pre-filled issue on GitHub.