简体   繁体   English

使用 setTimeout 理解 Javascript 循环

[英]Understanding Javascript loop with setTimeout

Why this function returns junk value followed by 5 5s为什么此函数返回垃圾值,后跟 5 5s

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

The observed behavior is as desired.观察到的行为是所期望的。 You can update your code to following您可以将代码更新为以下

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

The above paints the expected/correct values ie 0,1,2,3,4以上绘制了预期/正确的值,即 0,1,2,3,4

As per question, all the timeout functions are sharing a common variable j, hence, when the first logging was done, till then j was already updated to 5.根据问题,所有超时函数都共享一个公共变量 j,因此,当第一次记录完成时,直到那时 j 已经更新为 5。

So, you need to make sure you have private copies for each timeout function.因此,您需要确保每个超时函数都有私人副本。 Hence, in order to achieve the expected/correct values, you need to use closures.因此,为了达到预期/正确的值,您需要使用闭包。

The returned value is returned from setTimeout() .返回值从setTimeout()返回。 It is not junk value, it is the id of the timeout.它不是垃圾值,它是超时的 id。

timeoutID is the numerical ID of the timeout, which can be used later with window.clearTimeout(). timeoutID 是超时的数字 ID,稍后可以与 window.clearTimeout() 一起使用。

This id associated with timeout is used when clearing the timeout.清除超时时使用与timeout关联的此 id。

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

clearTimeout(timeoutID);

Another problem in your code is that it'll always print 5 in console.代码中的另一个问题是它总是在控制台中打印5 Because, the time when the setTimeout callback is executed, the loop is already executed and the value of j is 5 .因为,在 setTimeout 回调执行的时候,循环已经执行完毕, j值为5

To solve this use closure inside the loop.要解决此问题,请在循环内使用闭包

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM