JavaScript Sleep() function?

JavaScript doesn't have a built-in sleep() function like other languages (C's sleep(), Java's Thread.sleep(), Python's time.sleep()). However, we can create one using Promises and async/await.

Creating a Sleep Function

We can implement a sleep function using setTimeout() wrapped in a Promise:

function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

Using Sleep with Promises

<script>
function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

console.log("Start");
sleep(2000).then(() => {
    console.log("After 2 seconds");
});
</script>
Start
After 2 seconds

Using Sleep with Async/Await

The more elegant approach uses async/await syntax:

<script>
function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

async function demo() {
    console.log("Before sleep");
    await sleep(2000); // Wait 2 seconds
    console.log("After sleep");
}

demo();
</script>
Before sleep
After sleep

Example: Delayed Loop

<script>
function sleep(ms) {
    return new Promise(resolve => setTimeout(resolve, ms));
}

async function delayedLoop() {
    document.write("Starting countdown:<br>");
    
    for (let i = 3; i >= 1; i--) {
        await sleep(1000); // Wait 1 second
        document.write(i + "<br>");
    }
    
    await sleep(1000);
    document.write("Done!");
}

delayedLoop();
</script>
Starting countdown:
3
2
1
Done!

Key Points

  • sleep() function returns a Promise that resolves after the specified time
  • Use await with sleep in async functions for clean, readable code
  • Time is specified in milliseconds (1000ms = 1 second)
  • Sleep doesn't block the entire browser - other code can still run

Conclusion

JavaScript's sleep function is implemented using Promises and setTimeout. The async/await pattern provides the cleanest syntax for pausing execution in asynchronous functions.

Updated on: 2026-03-15T23:18:59+05:30

53K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements