Friday, 15 May 2015

javascript - loss of parameters when using windows.setTimeout -



javascript - loss of parameters when using windows.setTimeout -

i want show ongoing number javascript.

for have developed next example:

for(var i=0; i<100; i++) { window.settimeout(function() { alert(i); },1000*i); }

unfortunately number 100 shown every time. think because i reference?

how can changed in parameter passing?

the problem js not wait , proceeds finishing loop before timeouts expire. then, i 100.

to work around issue, timeout should have local reference of i. way, it's not referencing i 100 then, references i @ time of loop.

for(var i=0; i<100; i++) { (function(i){ //shadowing loop-i function-i window.settimeout(function() { //thus, callback referencing function //and not loop's alert(i); },1000*i); }(i)); }

javascript parameters reference parameter-passing settimeout

No comments:

Post a Comment