且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

while 循环中的 setTimeout() 方法

更新时间:2022-10-15 18:47:36

while 循环不会等待 setTimeout() 完成.您需要为每个设置不同的时间延迟以不同的时间执行它们,并使用闭包来保存 i 的值.同样在您的情况下,函数将最初执行,返回值设置为 setTimeout(),所以要么需要在匿名函数内部调用该函数,要么直接设置该函数.

var myFunc01 = function() {变量 i = 0;而 (i ";}, 1000 * i)})(i++)}};myFunc01();

<span id="d01"></span>

虽然 setInterval() 可以在这里使用

var myFunc01 = function() {变量 i = 0;//存储间隔 id 以备将来清除var intr = setInterval(function() {document.getElementById('d01').innerHTML += 100 - i + "
";//如果 `i` 达到 100,则清除间隔if (++i == 100) clearInterval(intr);}, 1000)}myFunc01();

<span id="d01"></span>

I have read the relevant pages on w3schools and other similar questions here but cannot seem to understand what's wrong about the following bit :

var myfunc03 = function (i) {
  document.getElementById('d01').innerHTML += 100-i+"<br>";
};

var myFunc01 = function() {
  i=0;
  while (i<100) {
    setTimeout(myfunc03(i), 1000)
    i++;
  }
};

when myFunc01(); is run.

There's no pause whatsoever and all possible values for i is listed at once.

Is there a logical mistake here?

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>