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

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

问题描述

我想这样做:

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

当然,javascript中没有睡眠功能,所以我试过以下: / p>

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天全站免登陆