Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make anonymous functions with local parameters

How do I make this javascript alert 0, 1 and 2 instead of 3 3's?

var vals = [1, 2, 3];
for(var i = 0; i < vals.length; i++)
{
    window.setTimeout(function() {alert(i);}, 1000);
}

I know the reason why it does this, but I can't figure out, how to pass i to the anonymous function.

like image 594
Tyilo Avatar asked Aug 23 '11 19:08

Tyilo


2 Answers

You can wrap this in a closure like so:

var vals = [1, 2, 3];

for(var i = 0; i < vals.length; i++) {
    (function(num) {
        window.setTimeout(function() {alert(vals[num]);}, 1000);
     })(i);
}

Try it: http://jsfiddle.net/qgL7h/

like image 52
Skylar Anderson Avatar answered Nov 14 '22 22:11

Skylar Anderson


var vals = [1, 2, 3];
function makeCallback(i)
{
    return function () {alert(i);};
}
for(var i = 0; i < vals.length; i++)
{
    window.setTimeout(makeCallback(i), 1000);
}
like image 34
Daniel Dickison Avatar answered Nov 14 '22 23:11

Daniel Dickison