This code outputs 10 10s instead of the expected 0 to 9, because the closure contains a reference to i, and then i has become 10 when the function is executed
function f1(){ for(var i = 0; i < 10; i++) { setTimeout(function() { alert(i); }, 1000); } } f1();
To solve the above problems, you can use self-executing 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 the e here will have a copy of i, and the reference is a reference to e, which avoids the above problem