Javascript: Mutation and Closure Results in Unexpected Behaviour

Posted by Gilbert on Stack Overflow See other posts from Stack Overflow or by Gilbert
Published on 2010-05-11T06:23:58Z Indexed on 2010/05/11 6:34 UTC
Read the original article Hit count: 233

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)?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about closures