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

17 Sep, 2019
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 timeThe 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:
function sleep(milliseconds) {    let timeStart = new Date().getTime();    while (true) {      let elapsedTime = new Date().getTime() - timeStart;      if (elapsedTime > milliseconds) {        break;      }    }  }
Example:
<!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>
Output:
Before sleeping:
After sleeping for 5000 milliseconds:
Method 2: Creating a new Promise and using the then() methodA 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 => {  return new Promise(resolve => setTimeout(resolve, milliseconds));}; sleep(timeToSleep).then(() => {  // code to execute after sleep});
Example:
<!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>
Output:
Before sleeping:
After sleeping for 5000 milliseconds:
JavaScript-Misc
Picked
JavaScript
Web Technologies
Web technologies Questions
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Remove elements from a JavaScript Array
Difference between var, let and const keywords in JavaScript
Difference Between PUT and PATCH Request
JavaScript | Promises
How to get character array from string in JavaScript?
Remove elements from a JavaScript Array
Installation of Node.js on Linux
How to fetch data from an API in ReactJS ?
How to insert spaces/tabs in text using HTML/CSS?
Difference between var, let and const keywords in JavaScript