Possible Duplicate:
Javascript closure inside loops – simple practical example
javascript variable scope/closure in loop after timeout
Can you please explain step by step why the results are different?
Snippet A (alerts 10)
for(var i=0; i<10; i++) if(i==3) setTimeout(function() {alert(i);}, 100);
Snippet B (alerts 3)
for(var i=0; i<10; i++) if(i==3) setTimeout((function(p) {
return function() {alert(p);}
} )(i), 100);
A variable’s scope is either the global scope (
windowin a browser) or a function.In the first case
iis defined in the scope containing theforloop. This is why it still changes until the end of the loop before the callback given tosetTimeoutis executed.In the second case, the intermediate function contains and keeps another variable,
p. Note that this would have worked without the test, as this would have been a different closure for eachsetTimeout.