What is the JavaScript version of sleep()?
What is the JavaScript equivalent of sleep(), and how can you pause code execution?Ever wanted to delay your code in JavaScript like you would with sleep() in other languages? Let’s explore how to simulate a sleep function using promises and async/await.
Well, JavaScript doesn’t have a built-in sleep() function like some other languages—but you can easily simulate it.
How to create a sleep function in [removed]
You can use setTimeout() inside a Promise along with async/await to create a pause or delay in execution.
Here's how it works:
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function doSomething() {
console.log("Start");
await sleep(2000); // waits for 2 seconds
console.log("End");
}
doSomething();
A few important points:
- sleep(ms) pauses execution for the specified number of milliseconds.
- It works only inside an async function since await is required.
- This doesn’t block the entire JavaScript thread (thanks to the event loop), so other code can continue running in the meantime.
Keep in mind:
- You shouldn't use sleep for long delays in UI-heavy applications—it can make things feel laggy.
- It’s super helpful in testing, animations, or simulating wait times in tutorials or mock APIs.
So yeah, even though JavaScript doesn’t give us a native sleep() function, the async/await combo makes it easy to replicate. Happy coding!