Javascript: Mutation and Closure Results in Unexpected Behaviour
- by Gilbert
for (var i = 0; i < 5; i++) {
var f = function() {
alert(i);
};
setTimeout(f, i * 1000);
}
If you run the code above, you'll get 5 alert boxes all saying "5"
Can someone explain why this happens?
Additionally, how can I change this code to get the result I want (5 alert boxes each with values 0, 1, 2, 3, 4)?