Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing arguments to javascript function [duplicate]

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);
like image 499
Jan Turoň Avatar asked Nov 25 '12 17:11

Jan Turoň


1 Answers

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.

like image 142
Denys Séguret Avatar answered Nov 12 '22 02:11

Denys Séguret