Full answer
Instead of wrapping setTimeout in new Promise yourself, import the ready-made versions:
const { setTimeout: sleep, setImmediate: yieldNow, setInterval: every, scheduler } = require('node:timers/promises');
- await sleep(ms, value): resolves with value after ms. A delay in an async function is one line.
- await yieldNow(): resolves in the next check phase, which lets pending I/O run. scheduler.yield() does the same job for splitting long work.
- scheduler.wait(ms, { signal }): like sleep, with an options object.
- for await (const tick of every(ms, value)): an async iterator that produces a value every ms. Use break to stop it, or pass a signal.
Options for all of them: { signal } to cancel (the promise rejects with AbortError), and { ref: false } to avoid keeping the process alive.
Common recipes:
- Timeout for any promise: Promise.race([work, sleep(ms).then(() => { throw new Error('timeout'); })]). Clear it with an AbortController, or the losing timer keeps running.
- Polling until a condition is true, with a pause between checks, using the setInterval iterator.
- Rate limiting in a loop: await sleep(100) between calls.
Important: setInterval from the promises module does not pile up calls when the loop body is slow. Ticks that happen while the body is running are not queued up forever, so slow work cannot create an endless backlog.
const { setTimeout: sleep, setInterval: every, setImmediate: yieldNow } = require('node:timers/promises');
async function waitUntil(check, { intervalMs = 10, timeoutMs = 200 } = {}) {
const controller = new AbortController();
const timeout = sleep(timeoutMs, undefined, { signal: controller.signal }).then(() => {
throw new Error('timed out waiting for the condition');
});
const polling = (async () => {
for await (const _ of every(intervalMs, undefined, { signal: controller.signal })) {
if (await check()) return 'condition became true';
}
})();
try {
return await Promise.race([timeout, polling]);
} finally {
controller.abort(); // stop the losing timer and the interval
}
}
async function main() {
console.log('value from sleep:', await sleep(5, 'rested'));
let attempts = 0;
const result = await waitUntil(() => ++attempts >= 3);
console.log(result, 'after', attempts, 'checks');
await waitUntil(() => false, { intervalMs: 10, timeoutMs: 50 }).catch((err) => console.log('second wait:', err.message));
let ticks = 0;
for await (const _ of every(5)) {
if (++ticks === 3) break;
}
console.log('interval ticks before break:', ticks);
const order = [];
setImmediate(() => order.push('immediate callback'));
Promise.resolve().then(() => order.push('promise callback'));
await yieldNow(); // resolves in the check phase, after the callbacks above
order.push('after yieldNow');
console.log('order:', order.join(' -> '));
}
main().catch((err) => console.log('unexpected:', err.message));The helper cancels both the timer and the interval in finally, so nothing keeps the process alive after the function returns. Save it as app.js and run it with node app.js. Output (Node.js v24.22.1, same on two runs): value from sleep: rested condition became true after 3 checks second wait: timed out waiting for the condition interval ticks before break: 3 order: promise callback -> immediate callback -> after yieldNow
Key points
- sleep is one line: await setTimeout(ms).
- setInterval from timers/promises is an async iterator.
- Pass a signal to cancel, ref: false to not hold the process.
- Cancel the timer in a timeout race, or it keeps running.
Common mistakes
- Racing a timeout promise and never cancelling its timer.
- Using sleep inside a loop for rate limiting without a signal.
- Assuming the promise version of setImmediate runs before callbacks that were queued earlier.
- Forgetting that the interval iterator ends only with break, return or a signal.
Follow-ups
- How is scheduler.yield different from setImmediate?
- How do you avoid keeping the process alive with a timer?
- How would you add jitter to a polling loop?
Tips
- Show the abort in finally, since that is the part people forget.
- Mention timers/promises replaces the old new Promise(r => setTimeout(r, ms)) pattern.
- Say ref: false for background timers.