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

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 with 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:

filter_none

edit
close

play_arrow

link
brightness_4
code

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

chevron_right


Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <title>
        JavaScript | sleep/wait before continuing
    </title>
</head>
  
<body>
    <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>
</body>
  
</html>

chevron_right


Output:

  • Before sleeping:
    infinite-loop-before
  • After sleeping for 5000 milliseconds:
    infinite-loop-after

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:

filter_none

edit
close

play_arrow

link
brightness_4
code

const sleep = milliseconds => {
  return new Promise(resolve => setTimeout(resolve, milliseconds));
};
 
sleep(timeToSleep).then(() => {
  // code to execute after sleep
});

chevron_right


Example:

filter_none

edit
close

play_arrow

link
brightness_4
code

<!DOCTYPE html>
<html>
  
<head>
    <title>
        JavaScript | sleep/wait before continuing
    </title>
</head>
  
<body>
    <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>
</body>
  
</html>

chevron_right


Output:

  • Before sleeping:
    promise-before
  • After sleeping for 5000 milliseconds:
    promise-after


My Personal Notes arrow_drop_up

Technical Writer Lets have an update

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.