Sleep for a number of milliseconds
Sleep for a number of milliseconds in JavaScript with a promise around setTimeout, or timers/promises in Node.js 24, and await it.
JavaScript has no sleep. A promise that resolves after a timer gives you one you can await.
import { setTimeout as sleep } from 'node:timers/promises';
const start = Date.now();
await sleep(100);
const waited = Date.now() - start;
console.log(waited >= 100);
const wait = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
await wait(50);
console.log('done');true
donenode:timers/promises exports a promise version of setTimeout, so no wrapper is needed in Node.js. The hand-written wait works in browsers too. Timers are not exact: the delay is a minimum, so the check is >= and the real wait can be a little longer. See the timers promises API.
It does not block the thread: other code can run during the wait. Do not use sleeping to wait for something to be ready, as in a retry loop with a fixed pause: wait for the event or poll with a limit. The Node.js version also accepts an AbortSignal to cancel the timer.