Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a variable with changing value in setTimeout function approach?

Tags:

javascript

Please let me know if I'm coming at this block on a wrong angle. I have a series of functions I'd like to fire off, and I'd like to be able to set them all up in a loop.

for(var jj = 0; jj<monster.frames.length;jj++){
    setTimeout(
        functionName(jj),
        1000*jj
    );
}

The problem is that when that when functionName(jj) is exectuted, it's being passed the value of jj which by that time has been changed to the last loop iteration value.

like image 266
Draculater Avatar asked Nov 21 '25 17:11

Draculater


1 Answers

You need to ensure the inner function has a new variable for every iteration. The easiest way to do this is to create a self-executing anonymous function which receives the variable as an argument. You also need to fix the way you are calling the function - right now you register the return value of functionName(jj) as a callback. This would only be ok if that function actually returned a function.

for(var jj = 0; jj<monster.frames.length;jj++){
    (function(jj) {
        setTimeout(
            function() { functionName(jj); },
            1000*jj
        );
    })(jj);
}

You can also use partial application to create a new function. However, old browsers do not support Function.prototype.bind so you'd have to add a shim for it.

for(var jj = 0; jj<monster.frames.length; jj++){
    setTimeout(functionName.bind(this, jj), 1000*jj);
}
like image 126
ThiefMaster Avatar answered Nov 23 '25 07:11

ThiefMaster



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!