Passing argument to setTimeout in a for loop

China☆狼群 提交于 2020-01-02 11:14:08

问题


I'm trying to learn how to pass an argument to setTimeout in a javacript for loop. Here is the example code. As it is currently written, setTimeout is passed the same exact i each time, not reflecting the different i's that are actually in the array.

var a=100;
for (i in array)
{   
    setTimeout("do_stuff(i, a)"), 2000);    
}

(I've seen somewhat similar questions and answers here, but the code examples are much more complicated. Answering this most basic example could much help others with the same problem. Thanks!!!)


回答1:


To use a string (which you shouldn't do), you 'd need to do this:

var a=100;
for (i in array)
{   
    setTimeout("do_stuff(" + i + ", a)"), 2000);    
}

A better answer would be to scope the i variable in a new function invocation, which returns an anonymous function to give to setTimeout().

function do_stuff( i, a ) {
    return function() {
        // do something with i and a
    }
}

var a=100;
for (i in array)
{   
    setTimeout(do_stuff( i , a ), 2000);    
}

Now do_stuff() returns a function that has a scoped reference to a new i and a variable. Because each call to do_stuff will have its own scope, the function you return will reference the correct values.


EDIT: Off topic, but if array is actually an Array, then you really shouldn't use for-in because that's meant for enumeration. With an Array, you typically want iteration of numeric indices, and as such should use a standard for loop.



来源:https://stackoverflow.com/questions/6564814/passing-argument-to-settimeout-in-a-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!