WEB TUTORIALS
PRACTICE EXAMPLES
HTML REFERENCES
CSS REFERENCES
PHP REFERENCES
Advertisements

How to Sleep Before Continuing in JavaScript

Topic: JavaScript / jQueryPrev|Next

Answer: Use the setTimeout() Method

You can simply use the setTimeout() method to sleep or wait before continuing to run the code in JavaScript. The time to delay in script execution is specified in milliseconds (thousandths of a second).

Let's try out the following example to understand how it basically works:

  • <!DOCTYPE html>
  • <html lang="en">
  • <head>
  • <meta charset="utf-8">
  • <title>JavaScript Wait Before Continuing</title>
  • <script>
  • function doStuff(){
  •     // Code to run before the pause
  •     var hintDiv = document.getElementById("hint");
  •     hintDiv.insertAdjacentHTML('afterbegin', '<p>An alert will be shown in 3 seconds.</p>');
  •  
  •     setTimeout(function(){
  •         // Code to run after the pause
  •         alert("This is really slow!");
  •     }, 3000);
  •  
  •     // This will also run before alert
  •     hintDiv.insertAdjacentHTML('beforeend', '<p>Alert is coming. Please do not go!</p>');
  • }
  • </script>
  • </head>
  • <body>
  •     <div id="hint"></div>
  •     <button type="button" onclick="doStuff()">Run Script</button>
  • </body>
  • </html>

As you've noticed in the previous example, JS code after setTimeout() method continue execution. However, if you want a real sleep where all further execution of JavaScript code should stop you can use the Promise constructor. Let's try out an example and see how it works:

  • <!DOCTYPE html>
  • <html lang="en">
  • <head>
  • <meta charset="utf-8">
  • <title>JavaScript Sleep Between Execution</title>
  • <script>
  • async function doStuff(){
  •     // Code to run before sleep
  •     var hintDiv = document.getElementById("hint");
  •     hintDiv.insertAdjacentHTML('afterbegin', '<p>An alert will be shown in 3 seconds.</p>');
  •  
  •     // Sleep for 3 seconds
  •     await new Promise(r => setTimeout(r, 3000));
  •  
  •     // Code to run after sleep
  •     alert("This is really slow!");
  •     hintDiv.insertAdjacentHTML('beforeend', '<p>You have seen the alert. Goodbye!</p>');
  • }
  • </script>
  • </head>
  • <body>
  •     <div id="hint"></div>
  •     <button type="button" onclick="doStuff()">Run Script</button>
  • </body>
  • </html>

The await operator is used to wait for a Promise. It can only be used inside an async function.


Related FAQ

Here are some more FAQ related to this topic:

Advertisements
Font Awesome Icon Classes

Your Feedback:

We would love to hear from you, please drop us a line.