---
title: "How do I sleep or wait in JavaScript?"
description: "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."
url: https://www.danny.engineering/answer/javascript/how-do-i-sleep-or-wait-in-javascript
author: Danny
published: 2026-11-27T00:00:00.000Z
updated: 2026-11-27T18:57:00.000Z
tags: ["Javascript"]
---

# How do I sleep or wait in JavaScript?

## 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.


```javascript
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

async function run() {
  console.log('Start');
  await sleep(1000);
  console.log('One second later');
}
```


## 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.


```javascript
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

async function showSteps(steps) {
  for (const step of steps) {
    render(step);
    await sleep(500);
  }
}
```


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.


```javascript
import { setTimeout as sleep } from 'node:timers/promises';

await sleep(2000);
console.log('Two seconds later');

const value = await sleep(100, 'done'); // resolves with "done"
```


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


```javascript
import { setInterval } from 'node:timers/promises';

for await (const _ of setInterval(5000)) {
  await checkHealth();
}
```


### 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.


```javascript
function sleep(ms, { signal } = {}) {
  return new Promise((resolve, reject) => {
    if (signal?.aborted) return reject(signal.reason);

    const id = setTimeout(resolve, ms);
    signal?.addEventListener('abort', () => {
      clearTimeout(id);
      reject(signal.reason);
    }, { once: true });
  });
}

const controller = new AbortController();
sleep(10_000, { signal: controller.signal }).catch(() => console.log('Cancelled'));
controller.abort();
```


### Wait between retries


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


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


## 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.

## Related reading

- [MDN: setTimeout()](https://developer.mozilla.org/en-US/docs/Web/API/Window/setTimeout)
- [Node.js: Timers Promises API](https://nodejs.org/api/timers.html)
