Passing argument to setTimeout in a for loop

2019-05-24 13:10发布

问题:

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.