SnippetJavaScript

Sleep/delay in async code

A one-line sleep(ms) you can await inside an async function, wrapping setTimeout in a Promise so nothing else on the page blocks.

Last updated

Snippetjavascript
function sleep(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}

// inside an async function:
// await sleep(500);
// runs after roughly 500ms

How it works

JavaScript has no built-in blocking sleep, and that's deliberate — a real blocking sleep would freeze the single thread the page or server runs on, including its UI and every other pending request. Wrapping setTimeout in a Promise gives you the same-looking `await sleep(500)` call site without ever blocking anything: the event loop stays free to handle other work while the timer counts down.

resolve is passed directly as setTimeout's callback rather than wrapped in an arrow function, since setTimeout calls it with no arguments the Promise executor cares about — one less closure for the same effect.

Edge cases to know

  • Only the async function that awaits sleep() pauses — everything else (other requests, other event handlers, timers) keeps running exactly as if sleep() were never called.
  • The delay is a minimum, not a guarantee: if the event loop is busy when the timer fires, the resolution — and whatever runs after the await — is pushed back accordingly.
  • There's no way to cancel a pending sleep with this version; if you need that, pair it with an AbortSignal and reject when the signal fires.

Related in Snippets