How to add delay in a loop in JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

To add delay in a loop, use the setTimeout() metod in JavaScript. Following is the code for adding delay in a loop −

Example

 Live Demo

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 18px;
      font-weight: 500;
      color: blueviolet;
   }
</style>
</head>
<body>
<h1>Adding delay in a loop in JavaScript</h1>
<div class="result"></div>
<button class="Btn">Start</button>
<h3>Click on the above button to start the loop</h3>
<script>
   let BtnEle = document.querySelector(".Btn");
   let resEle = document.querySelector(".result");
   BtnEle.addEventListener("click", () => {
      for (let i = 0; i < 10; i++) {
         setTimeout(function () {
            resEle.innerHTML += "i = " + i + "<br>";
         }, 2000 * i);
      }
   });
</script>
</body>
</html>

Output

On clicking the ‘START’ button, 3 there will be delay after each iteration −


raja
Published on 16-Jul-2020 13:43:27
Advertisements