Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Variables in a setTimeout inside a loop (scope issue) [duplicate]

Possible Duplicate:
Javascript closure inside loops - simple practical example
Calling setTimeout function within a loop

before calling this a duplicate, I looked on the internet and everyone seemed to have different problems. If anybody could help me with this particular one, it'd be greatly appreciated.

Basicaly, what I have is two for loops nested inside a 3rd one.

for (a=0 ... a++) {
    for (b=0 ... b++) {
        setTimeout( ... + a + ..., 1000*b);
    }
    for (c=0 ... c++) {
        setTimeout( ... + a + ..., 1000*c);
    }
}

This is some pseudo code just to avoid the junk, but basically I want to pass the a value to the callback function triggered by the timer. The problem comes from the fact a is being incremented, so when then event is fired, the function has the last value of a instead of the one one it one registered.

I can think of it like a reference or a pointer in C/C++, this is really annoying. Any way to give it a permanent value?


1 Answers

A closure in it's simplest form would do the trick:

for (a=0 ... a++) {
    (function(a){
       for (b=0 ... b++) {
           setTimeout( ... + a + ..., 1000*b);
       }
       for (c=0 ... c++) {
           setTimeout( ... + a + ..., 1000*c);
       }
    })(a);
}

To take Pointys answer into account: One should never pass a string to setTimeout.

You can use the 3-parameters form of setTimeout and pass a function (or a reference to a function), the time value and the parameters for the function:

for (a=0 ... a++) {
     for (b=0 ... b++) {
         setTimeout( function(x){ /*do stuff, using x */}, 1000*b, a);
     }
}

Note however, that unfortunately the 3 parameter form does not work in Internet Explorer.

like image 80
Christoph Avatar answered Jul 25 '26 02:07

Christoph