Javascript setTimeOut in For Loop Behaviour -


i curious why , how javascript interpreter outputs following

5 5 5 5 5 

when running code:

for(var i=0;i<5;i++){ settimeout(function(){console.log(i);},200);   }; 

can provide thorough explanation?

it's chronology.

remember timeout synchronous operation delayed, time runs, consults i , finds value 5. because last action of (synchronous) loop set value 5: reached 4 (the last iteration of loop) , i++ made 5.

if want output 0-4 retain timeout, need capture current, iterative value of i @ time create timeout. can passing immediately-executing function:

for(var i=0;i<5;i++)     settimeout((function(i) { return function(){ console.log(i); }; })(i),200); 

Comments

Popular posts from this blog

javascript - Count length of each class -

What design pattern is this code in Javascript? -

hadoop - Restrict secondarynamenode to be installed and run on any other node in the cluster -