A reusable sleep helper
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function run() {
console.log("start");
await sleep(1000);
console.log("one second later");
}
The sleep function returns a promise; await pauses run until that promise resolves.
Pausing inside a loop
async function countdown() {
for (let i = 3; i > 0; i--) {
console.log(i);
await sleep(1000);
}
console.log("Go!");
}
Because await sits inside an async loop, each number prints one second apart.
Why a plain delay loop is wrong
// Do NOT do this — it freezes everything:
const end = Date.now() + 1000;
while (Date.now() < end) {}
A busy loop blocks the single JavaScript thread, so the page stops responding to clicks and rendering. Always use the async approach instead.
Which approach should you use?
- await sleep(ms) — the correct way to pause inside async code.
- setTimeout(callback, ms) — when you just want to run something later, without awaiting.
- Common mistake: blocking with a
whileloop, which freezes the whole page.
Frequently asked questions
Why is there no built-in sleep in JavaScript?
JavaScript runs on a single thread, so a true blocking sleep would freeze the page. The async promise pattern pauses your function while keeping the page responsive.
Can I sleep outside an async function?
Not with await. Outside async code, use setTimeout(callback, ms) to schedule the work for later instead of pausing in place.
Want to understand promises and async/await? Our free JavaScript course covers them with live examples.