Skip to content
jshacks.dev
Async

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.

1 min read
Summarize in AI

JavaScript has no sleep. A promise that resolves after a timer gives you one you can await.

JavaScript
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');
Text
true
done

node: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.

Taggednode 24
Share

More snippets

Node.js

Read a text file with fs promises

Read a text file with fs promises in Node.js: await readFile with an encoding, and catch the error code when the file is missing. Node.js 24.

1 min read
Node.js

Write CSV rows with a stream

Write CSV rows to a file stream in Node.js 24, quote fields that hold commas or quotes per RFC 4180, and wait for drain so memory stays flat.

2 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.