Javascript 如何在迭代列表操作中使用 setTimeout? [英] Javascript how to use setTimeout on an iterative list operation?

查看:30
本文介绍了Javascript 如何在迭代列表操作中使用 setTimeout?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想做这样的事情:

for(var i=0;i<aList.length;i++)
{
    aList[i].doSomething();
    sleep(500);
}

当然,javascript 中没有 sleep 功能,所以我尝试了以下操作:

Of course, there's no sleep function in javascript so I tried the following:

for(var i=0;i<aList.length;i++)
{
    setTimeout(function(){
        aList[i].doSomething();
    },500);  
}

然而,现在它说 aList[i] 没有定义.由于匿名函数是一个闭包,它实际上是从外部函数的作用域中读取aList[i],因此在setTimeout中的函数运行时,i已经发生了变化.

However, now it says aList[i] is not defined. Since the anonymous function is a closure, it is actually reading aList[i] from the scope of the outside function, and thus by the time the function in setTimeout is being run, i has already changed.

有什么方法可以做到这一点?

What is a way to accomplish this?

推荐答案

模拟 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.

这篇关于Javascript 如何在迭代列表操作中使用 setTimeout?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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