且构网

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

Javascript 如何在迭代列表操作中使用 setTimeout?

更新时间:2023-10-29 23:30:34

模拟 JavaScript 1.7 的 let 的快速修复方法是将其包装在函数中:

A quick fix to emulate JavaScript 1.7's let is to wrap it in a function:

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

我还修复了一个小错误,其中脚本将暂停 500 秒,然后执行所有这些错误.setTimeout 是非阻塞的.

I also added a fix to a little bug in which the script will pause 500 seconds, then execute all of them. setTimeout is non-blocking.