Node.js
Await a delay with timers/promises
Use the promise-based setTimeout API for an awaitable delay in Node.js. Import it under a clear name so it is not confused with the callback-based global function.
Worked example
Node.js example · save as example.mjs and run node example.mjs
import {setTimeout as delay} from "node:timers/promises";
const value = await delay(5, "ready");
console.log(value);How it works
The delay resolves with the supplied value after the timer becomes eligible to run. Await keeps the control flow sequential without wrapping a callback in a hand-written promise. This can simplify retry spacing or a short pause in a script.
Limits and mistakes
A timer is not a precise scheduling guarantee; a busy event loop can delay execution. Sleeping also does not make a rate-limited API safe without considering concurrent callers and the provider’s actual rules. Prefer an explicit readiness condition when waiting for another service.
Check the result
Expect ready. Avoid tests that require the timer to fire at an exact millisecond, and check that cancellation is handled if a longer wait should be interruptible.
Sources
Reference documentation for the behavior used in this guide: