Delay execution of script in JavaScript

How to delay execution of script in JavaScript

Posted by Ervin Adams on September 29, 2022

Delay execution of script in JavaScript

How to delay execution of script in JavaScript

Posted by Ervin Adams on September 29, 2022

Here is how you can delay a script using JavaScript

Use the method setTimeout() to delay script execution.

Here is a demo below:

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Wecode101 delay execution of script in JavaScript</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
</head>
<body>
  <main>
    <!--Main layout-->
    <div class="container">
        <div class="col-9 pt-5 mx-auto">
            <p id="msg"></p>
        </div>
    </div>
  </main>
</body>
</html>

JavaScript

const delay = setTimeout(delayMsg, 5000);

function delayMsg() {
  document.getElementById("msg").innerHTML = "This message is delayed by 5 seconds."
}