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 (window
in a browser) or a function.
In the first case i
is defined in the scope containing the for
loop. This is why it still changes until the end of the loop before the callback given to setTimeout
is 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 each setTimeout
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With