In JavaScript, there isn’t a built-in sleep() function like in some other programming languages, but you can still pause or delay execution using some clever tricks — especially with modern async/await syntax. So, if you're wondering how to make your code wait before moving on, here are a few ways to do it:
1. Using setTimeout()
This is the most basic approach. It sets a timer and runs a function after a specified delay.
setTimeout(() => {
console.log("This runs after 2 seconds");
}, 2000);
But remember — this doesn’t actually pause your code, it just schedules something for later.
2. Using async/await with Promises
If you want your code to wait properly, this is the way to go:
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
async function example() {
console.log("Wait for it...");
await sleep(2000);
console.log("2 seconds later!");
}
example();
3. Why not a loop?
You might be tempted to use a while loop to create a delay, but this can freeze your browser or app:
// BAD practice – blocks everything
let start = Date.now();
while (Date.now() - start < 2000>
Summary:
- Use setTimeout() for non-blocking delays.
- Use async/await + Promises for actual pause-and-resume behavior.
- Avoid blocking loops!