More JavaScript answers

by Danny
Published 2 min read

JavaScript has no blocking sleep, but you can pause an async function by awaiting a promise around setTimeout. Covers Node's timers/promises, cancelling and loops.

The short answer

#

Wrap setTimeout in a promise and await it inside an async function. The function pauses for that many milliseconds while the rest of the page or server keeps running. In Node, import the promise version of setTimeout from node:timers/promises instead of writing your own.


_10
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
_10
_10
async function run() {
_10
console.log('Start');
_10
await sleep(1000);
_10
console.log('One second later');
_10
}

Why it happens

#

JavaScript runs your code on a single main thread with an event loop. If a function could block that thread for a second, nothing else could happen: no clicks, no rendering, no other requests on a server. So the language has no sleep that freezes execution.

What it does have is timers. setTimeout schedules a callback for later and returns straight away. Putting it inside a promise lets await pause just the current async function until the timer fires, while the event loop carries on with other work. That is why the wait only works inside an async function or at the top level of a module.

How to fix it

#

Use a sleep helper in the browser

The one-line helper above is all most browser code needs. Use it inside any async function, including loops.


_10
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
_10
_10
async function showSteps(steps) {
_10
for (const step of steps) {
_10
render(step);
_10
await sleep(500);
_10
}
_10
}

Use a for...of loop, not forEach. forEach does not wait for an async callback, so every step would run at once.

Use timers/promises in Node

Node has a built-in promise version of setTimeout. Rename it on import so it does not clash with the global one.


_10
import { setTimeout as sleep } from 'node:timers/promises';
_10
_10
await sleep(2000);
_10
console.log('Two seconds later');
_10
_10
const value = await sleep(100, 'done'); // resolves with "done"

The same module also exports setInterval, which returns an async iterator for repeating work.


_10
import { setInterval } from 'node:timers/promises';
_10
_10
for await (const _ of setInterval(5000)) {
_10
await checkHealth();
_10
}

Make the wait cancellable

A long wait should stop if the user leaves the page or the request is cancelled. Node's version accepts an AbortSignal, and you can add the same support to your own helper.


_15
function sleep(ms, { signal } = {}) {
_15
return new Promise((resolve, reject) => {
_15
if (signal?.aborted) return reject(signal.reason);
_15
_15
const id = setTimeout(resolve, ms);
_15
signal?.addEventListener('abort', () => {
_15
clearTimeout(id);
_15
reject(signal.reason);
_15
}, { once: true });
_15
});
_15
}
_15
_15
const controller = new AbortController();
_15
sleep(10_000, { signal: controller.signal }).catch(() => console.log('Cancelled'));
_15
controller.abort();

Wait between retries

A common real use is backing off between attempts at a flaky request.


_10
async function fetchWithRetry(url, attempts = 3) {
_10
for (let i = 0; i < attempts; i++) {
_10
try {
_10
return await fetch(url);
_10
} catch (error) {
_10
if (i === attempts - 1) throw error;
_10
await sleep(2 ** i * 500); // 500 ms, 1 s, 2 s
_10
}
_10
}
_10
}

Common pitfalls

#
  • Calling sleep(1000) without await. The promise is created, but the next line runs immediately.
  • Using a busy loop such as while (Date.now() < end). It really does block, freezing the page or stalling every request on the server.
  • Expecting exact timing. A timer fires no sooner than the delay, but it can be later if the thread is busy, and browsers slow timers down in background tabs.
  • Waiting a fixed time for something to be ready, such as an element or a file. Wait for the actual event or poll with a limit instead, or the code breaks on slower machines.
  • Using sleep in tests to wait for updates. Prefer fake timers or the testing library's built-in waiting helpers so tests stay fast and reliable.
#

Was this resource helpful?