Open In App

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

Improve
Improve
Like Article
Like
Save
Share
Report

JavaScript, unlike other languages, does not have any method to simulate a sleep() function. There are some approaches that can be used to simulate a sleep function. 

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

The time that the sleep function starts is first found using the new Date().getTime() method. This returns the number of milliseconds passed since the Epoch time. An infinite while loop is started. The elapsed time is calculated by subtracting the current time from the starting time. If-statement checks whether the elapsed time is greater than the given time (in milliseconds). On satisfying the condition, a break statement is executed, breaking out of the loop. The sleep function now ends and the lines of code written after the sleep function will now execute. This type of sleep which uses an infinite loop stall the processing of the rest of the script and may cause warnings from the browser. It is not encouraged to use this type of sleep function for a long duration. 

Syntax: 

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

Example: 

html




<h1 style="color: green">GeeksforGeeks</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 miliiseconds
    sleep(5000);
      
    console.log("Sleep completed successfully");
</script>


Output:

 

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

A new Promise is created which contains a setTimeout() function. The setTimeout() function is used to execute a function after a specified amount of time. The resolved state of the Promise is used inside the setTimeout() function to finishing it after the timeout. The then() method can be used to execute the required function after the Promise has finished. This simulates a waiting time for a function. This method does not block the asynchronous nature of JavaScript and is a preferred method for delaying a function. It is also only supported with the ES6 standard due to the use of Promises. 

Syntax: 

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

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

Example: 

html




<h1 style="color: green">GeeksforGeeks</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 miliiseconds and then execute function
    sleep(5000).then(() => {
        console.log("Sleep completed successfully");
    });
</script>


Output:

 



Last Updated : 23 Jan, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads