This code outputs 10 10s instead of the expected 0 to 9, because there is a reference to i in the closure, and then when the function is executed, i has become 10
function f1(){for(var i = 0; i < 10; i++) {setTimeout(function() {alert(i); }, 1000);}}f1();To solve the above problems, you can use self-executed anonymous functions.
function f2(){for(var i = 0; i < 10; i++) {(function(e) {setTimeout(function() {alert(e); }, 1000);})(i);}}f2();The anonymous function here takes i as a parameter, and here e will have a copy of i, and the reference is a reference to e, which avoids the above problems.