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.
You can wrap this in a closure like so:
Try it: http://jsfiddle.net/qgL7h/