while循环内的setTimeout()方法 [英] setTimeout() method inside a while loop

查看:113
本文介绍了while循环内的setTimeout()方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在这里阅读了有关w3schools的相关页面和其他类似问题,但似乎无法理解以下内容出了什么问题:

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++;
  }
};

运行 myFunc01(); 时.

没有任何暂停,并且同时列出了i的所有可能值.

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

这里有逻辑上的错误吗?

Is there a logical mistake here?

推荐答案

while 循环将不等待 setTimeout() ,因此您需要在匿名函数内部调用该函数或直接设置该函数.

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>


尽管 setInterval() 可以在此处使用

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>

这篇关于while循环内的setTimeout()方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆