How do you implement a sleep or async delay function in JavaScript?
Create a Promise wrapper around **setTimeout** (const sleep = ms => new Promise(r => setTimeout(r, ms))) and **await** it inside an async` function to pause execution without blocking the main thread.
Reusable sleep() Helper (Recommended)
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function runTask() {
console.log("Starting task...");
await sleep(2000); // Pauses for 2 seconds non-blockingly
console.log("Resumed after 2 seconds!");
}
runTask();
Important Rule
Never use a synchronous while loop with Date.now() to simulate sleep—it freezes the entire browser UI and blocks the Node.js event loop.
'
You must log in or register to comment.
