How to add sleep/wait function before continuing in JavaScript?

Adding a sleep/wait function in JavaScript means pausing the execution of code for a specified period. This can be done using `setTimeout` for asynchronous waits or through promises and async/await for more readable and controlled delays in asynchronous functions.

Method 1: Using an infinite loop to keep checking for the elapsed time.

Using new Date().getTime(), an infinite loop calculates elapsed time until it matches the desired wait. This halts script execution and may cause browser warnings. Such blocking sleeps are discouraged for long durations due to their impact on performance and responsiveness.

Syntax: 

function sleep(milliseconds) {
    let timeStart = new Date().getTime();
        while (true) {
        let elapsedTime = new Date().getTime() - timeStart;
        if (elapsedTime > milliseconds) {
        break;
        }
    }
}

Example: 

html
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript Sleep Example</title>
    <style>
        h1 {
            color: green;
        }
    </style>
</head>

<body>
    <h1>w3wiki</h1>
    <b>JavaScript | sleep/wait before continuing</b>
    <p>
        A sleep of 5000 milliseconds is simulated.
        Check the console for the output.
    </p>
    <script>
        function sleep(milliseconds) {
            let timeStart = new Date().getTime();
            while (true) {
                let elapsedTime = new Date().getTime() - timeStart;
                if (elapsedTime > milliseconds) {
                    break;
                }
            }
        }

        console.log("Hello World");
        console.log("Sleeping for 5000 milliseconds");

        // sleep for 5000 milliseconds
        sleep(5000);

        console.log("Sleep completed successfully");
    </script>
</body>

</html>

Output:

Method 2: Creating a new Promise and using the then() method.

A new Promise with setTimeout() delays execution without blocking JavaScript’s asynchronous nature. The Promise resolves after the timeout, and the then() method executes the next function. Preferred for delays, this method requires ES6 due to Promises support.

Syntax: 

const sleep = milliseconds =&gt; {
    return new Promise(resolve =&gt; setTimeout(resolve, milliseconds));
};

sleep(timeToSleep).then(() =&gt; {
    // code to execute after sleep
});

Example: 

html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>JavaScript Sleep Example</title>
    <style>
        h1 {
            color: green;
        }
    </style>
</head>
<body>
    <h1>w3wiki</h1>
    <b>JavaScript | sleep/wait before continuing</b>
    <p>
        A sleep of 5000 milliseconds is simulated. Check the console for the output.
    </p>
    <script>
        const sleep = milliseconds => {
            return new Promise(resolve => setTimeout(resolve, milliseconds));
        };
        
        console.log("Hello World");
        console.log("Sleeping for 5000 milliseconds");
        
        // sleep for 5000 milliseconds and then execute function
        sleep(5000).then(() => {
            console.log("Sleep completed successfully");
        });
    </script>
</body>
</html>

Output:



Contact Us