setTimeout() method inside a while loop [duplicate]

The while loop will not wait for setTimeout() to complete. You need to set different time delay for each to execute them with different times and use closure for holding the value of i. Also in your case, function will be executed initially and return value is setting as argument in setTimeout(), so either you need to call the function inside an anonymous function or set the function directly.

var myFunc01 = function() {
  var i = 0;
  while (i < 100) {
    (function(i) {
      setTimeout(function() {
        document.getElementById('d01').innerHTML += 100 - i + "<br>";
      }, 1000 * i)
    })(i++)
  }
};

myFunc01();
<span id="d01"></span>

Although setInterval() can be used here

var myFunc01 = function() {
  var i = 0;
  // store the interval id to clear in future
  var intr = setInterval(function() {
    document.getElementById('d01').innerHTML += 100 - i + "<br>";
    // clear the interval if `i` reached 100
    if (++i == 100) clearInterval(intr);
  }, 1000)

}

myFunc01();
<span id="d01"></span>

Leave a Comment