Raz*_*orm 0 javascript closures anonymous-function settimeout
我想做这样的事情:
for(var i=0;i<aList.length;i++)
{
aList[i].doSomething();
sleep(500);
}
Run Code Online (Sandbox Code Playgroud)
当然,javascript中没有睡眠功能所以我尝试了以下内容:
for(var i=0;i<aList.length;i++)
{
setTimeout(function(){
aList[i].doSomething();
},500);
}
Run Code Online (Sandbox Code Playgroud)
但是,现在它说没有定义aList [i].由于匿名函数是一个闭包,它实际上是从外部函数的范围读取aList [i],因此在运行setTimeout中的函数时,i已经发生了变化.
有什么方法可以实现这个目标?
模拟JavaScript 1.7的快速修复方法let是将其包装在一个函数中:
for(var i=0; i < aList.length; i++) {
(function(i) {
setTimeout(function() {
aList[i].doSomething();
}, 500 * i); // <-- You need to multiply by i here.
})(i);
}
Run Code Online (Sandbox Code Playgroud)
我还添加了一个小错误的修复程序,其中脚本将暂停500秒,然后执行所有这些.setTimeout是非阻塞的.