使用 setTimeout 理解 Javascript 循环

Understanding Javascript loop with setTimeout

为什么这个函数returns垃圾值后跟5个5s

for (var j = 0; j < 5; j++) {
    setTimeout(function () {
        console.log(j);
    }, 1000);
}

观察到的行为符合预期。您可以将代码更新为以下

for(var j=0;j<5;j++){
  (function(index){
    setTimeout(function(){console.log(index);},1000);
  })(j);
}

上面绘制了 expected/correct 值,即 0,1,2,3,4

根据问题,所有超时函数都共享一个公共变量 j,因此,当第一次记录完成时,j 已经更新为 5。

因此,您需要确保每个超时函数都有私有副本。因此,为了实现 expected/correct 值,您需要使用闭包。

返回值是从setTimeout()返回的。不是垃圾值,是超时的id。

timeoutID is the numerical ID of the timeout, which can be used later with window.clearTimeout().

这个与timeout关联的id在清除超时时使用。

var timeoutID = setTimeout(function() {
    console.log('hello');
}, 1000);

clearTimeout(timeoutID);

代码中的另一个问题是它总是在控制台中打印 5。因为,setTimeout回调执行的时候,循环已经执行完了,j的值为5.

要解决此问题,请在循环内使用 闭包

for (var j = 0; j < 5; j++) {
  (function(j) {
    setTimeout(function() {
      document.write(j + '<br />');
    }, 1000);
  }(j));
}