How to Sleep Before Continuing in JavaScript

  190 views   3 months ago Javascript

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>

 

Author : Harsukh Makwana
Harsukh Makwana

Hi, My name is Harsukh Makwana. i have been work with many programming language like php, python, javascript, node, react, anguler, etc.. since last 5 year. if you have any issue or want me hire then contact me on harsukh21@gmail.com

Related Articles