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:
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/
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);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With