How to add sleep/wait function before continuing in JavaScript? Last Updated : 04 Jun, 2024 Summarize Comments Improve Suggest changes Share Like Article Like Report 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>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 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 => { return new Promise(resolve => setTimeout(resolve, milliseconds)); }; sleep(timeToSleep).then(() => { // 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>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 milliseconds and then execute function sleep(5000).then(() => { console.log("Sleep completed successfully"); }); </script> </body> </html> Output: Comment More infoAdvertise with us Next Article How to create an Asynchronous function in Javascript? S sayantanm19 Follow Improve Article Tags : JavaScript Web Technologies JavaScript-Questions Similar Reads How to Execute setInterval Function without Delay for the First Time in JavaScript? When working with JavaScript, the setInterval function is a powerful tool for executing a block of code repeatedly at specified intervals. The setInterval() method always invokes the function after the delay for the first time. Approach 1: Calling the function once before executing setInterval:Invok 2 min read How to create an Asynchronous function in Javascript? JavaScript is a single-threaded and synchronous language. The code is executed in order one at a time. But Javascript may appear to be asynchronous in some situations. Example: HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title 6 min read How to Delay a Function Call in JavaScript ? Delaying a JavaScript function call involves executing a function after a certain amount of time has passed. This is commonly used in scenarios where you want to postpone the execution of a function, such as in animations, event handling, or asynchronous operations. Below are the methods to delay a 2 min read How to set the cursor to wait in JavaScript ? In JavaScript, we could easily set the cursor to wait. In this article, we will see how we are going to do this. Actually, it's quite an easy task, there is a CSS cursor property and it has some values and one of the values is wait. We will use the [cursor: wait] property of CSS and control its beha 3 min read How to call a function repeatedly every 5 seconds in JavaScript ? In JavaScript, the setInterval() method allows you to repeatedly execute a function or evaluate an expression at specified intervals. This method is particularly useful for performing periodic tasks like updating a user interface or making repeated API calls.Syntax:Â setInterval(function, millisecond 2 min read How to wait for multiple Promises in JavaScript ? Waiting for multiple promises in JavaScript involves using Promise.all() or Promise.allSettled() methods. These methods accept an array of promises as input. Promise.all() waits for all promises to either resolve or reject, providing a single promise that resolves with an array of results or rejects 3 min read Like