javascript - Passing argument to setTimeout in a for loop -


i'm trying learn how pass argument settimeout in javacript loop. here example code. written, settimeout passed same exact each time, not reflecting different i's in array.

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

(i've seen similar questions , answers here, code examples more complicated. answering basic example others same problem. thanks!!!)

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

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

a better answer scope i variable in new function invocation, returns anonymous function give settimeout().

function do_stuff( i, ) {     return function() {         // ,     } }  var a=100; (i in array) {        settimeout(do_stuff( , ), 2000);     } 

now do_stuff() returns function has scoped reference new i , a variable. because each call do_stuff have own scope, function return reference correct values.


edit: off topic, if array array, shouldn't use for-in because that's meant enumeration. array, typically want iteration of numeric indices, , such should use standard for loop.


Comments

Popular posts from this blog

c++ - Is it possible to compile a VST on linux? -

java - Output of Eclipse is rubbish -

jquery - Confused with JSON data and normal data in Django ajax request -