What is the JavaScript version of sleep()?

JavaScript doesn't have a built-in sleep() function like other languages, but you can create one using Promise and setTimeout() with async/await.

Creating a Sleep Function

The most common approach is to create a promise-based sleep function that works with async/await:

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

async function displayMessages() {
    document.write('Wait for 3 seconds!<br>');
    await sleep(3000);
    document.write('After 3 seconds!<br>');
    
    document.write('Wait for 2 more seconds!<br>');
    await sleep(2000);
    document.write('Done!');
}

displayMessages();
</script>
</body>
</html>

How It Works

The sleep() function returns a Promise that resolves after the specified number of milliseconds. When used with await, it pauses execution of the async function without blocking the main thread.

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

async function example() {
    console.log('Starting...');
    await sleep(2000);  // Wait 2 seconds
    console.log('2 seconds later');
    await sleep(1000);  // Wait 1 second
    console.log('Done!');
}

example();
Starting...
2 seconds later
Done!

Alternative: Using setTimeout Directly

Without async/await, you can use setTimeout() with callbacks:

<!DOCTYPE html>
<html>
<body>
<script>
console.log('Starting...');

setTimeout(() => {
    console.log('After 2 seconds');
    
    setTimeout(() => {
        console.log('After 4 seconds total');
    }, 2000);
}, 2000);
</script>
</body>
</html>

Comparison

Method Readability Modern JS
Promise + async/await High Yes
setTimeout callbacks Low (callback hell) No

Conclusion

Use Promise with async/await to create a clean sleep function in JavaScript. This approach is non-blocking and follows modern JavaScript best practices.

Updated on: 2026-03-15T21:42:21+05:30

477 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements