How to wait in JavaScript — and why await inside forEach doesn't wait

In Python you write time.sleep(1) and the program waits a second. JavaScript simply has no such command. You search for "sleep," find nothing, and write a loop that spins idle for a second. The whole page freezes: buttons don't click, animations stop.
Good news: a real pause in JS is one line. Bad news: there's a spot where it silently doesn't work. Let's cover both.
Why JavaScript has no sleep
A page in the browser has one thread. It draws, handles clicks and runs your code. If the code "sleeps," everything sleeps. So JS works differently: not "stop," but "remind me in a second, and do other things meanwhile."
setTimeout handles the "remind me." To make code read like a normal pause, you wrap it in a promise and use await. If async still sounds fuzzy — see the explainer; the general idea is enough here.
Step by step: a pause that works
-
Create a delay function. One line you can copy into any project:
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));It returns a promise that resolves after
msmilliseconds. -
Make the function that needs the pause async. Put
asyncin front of it:async function greet() { console.log("Hi"); await sleep(1000); console.log("…a second later"); }awaitonly works inside anasyncfunction (or at the top level of a module). -
For a pause inside a loop, use
for...of. For example, send three requests a second apart so you don't hit a rate limit:for (const id of ids) { await fetch("/api/items/" + id); await sleep(1000); }Every step of the loop honestly waits for the previous one.
-
Check that the pause happened. Measure time before and after with
Date.now(). Three iterations of one second should take about three seconds.
The trap: forEach doesn't wait
Here's the non-obvious part. AI often writes this:
ids.forEach(async (id) => {
await sleep(1000);
await fetch("/api/items/" + id);
});
console.log("all sent");
Looks logical. But "all sent" prints immediately, and all requests fire at once a second later. The pause isn't between them — it's one shared pause.
Why? forEach calls the function for each item and ignores what it returns. An async function returns a promise — and forEach just throws it away. We checked in Node 22: right after such a forEach, the results array is empty and 0 ms have passed.
Hence the rule:
- Need them one by one —
for...ofwithawait. Three 100 ms requests take about 300 ms. - Need them in parallel but wait for all —
await Promise.all(ids.map(...)). The same three take about 100 ms. forEachwithasync— almost always a bug.
Add a delay between requestsIn the sendAll function I loop over an ids array and call fetch for each. Requests must go strictly one after another with a 1 second pause between them, and after the last one log "done". Use a sleep function built on setTimeout and a for...of loop with await, not forEach. Show the full final code.What you get
Console messages appear with pauses while the page stays alive: buttons click, scrolling works. Requests go out one at a time, and the server doesn't answer with a 429 error. And "done" prints at the very end, not the beginning.
How to wait no longer than a limit — a timeout for a request
The reverse task: not "wait a second" but "don't wait more than five seconds." Say the server hangs and the user stares at a spinner. fetch has a ready-made answer:
const res = await fetch("/api/report", {
signal: AbortSignal.timeout(5000),
});
After five seconds the request is cancelled and await throws an error. Catch it with try/catch and show a clear message. And if you want to retry, pause between attempts and grow the pause: 1, 2, 4 seconds. That gives the server time to recover.
Why is the pause longer in a background tab?
Browsers save battery by slowing timers in inactive tabs — usually to no more than once a second. Your sleep(100) in the background may become a full second. For accurate time, check Date.now() rather than counting ticks.
Is setTimeout with zero instant?
No. setTimeout(fn, 0) means "as soon as you're free," not "right now." The current code finishes first, and only then does fn run.
Should I put pauses in tests?
Better not. sleep(2000) "so the page has time to load" makes tests slow and flaky: on a fast machine the pause is wasted, on a slow one it's too short. It's more reliable to wait for a specific event — a button appearing or a server response. Testing tools do this out of the box.
Can I pause without async?
You can pass a callback to setTimeout — code that runs later. But for a chain of pauses this quickly turns into a staircase of nested functions. With await it reads more simply.
The AI Architect 2027 course: step by step from computer basics to your own app and first customers. 543 short lessons on your phone.





