0

I have small doubt in the below code

for(var i=1; i<6; i++) {
   console.log('Outside: ',i);
   setTimeout(function(){ console.log('Inside: ',i); }, 1000);
}

Result of above code: is

Outside: 1
Outside: 2
Outside: 3
Outside: 4
Outside: 5
Inside: 6
Inside: 6
Inside: 6
Inside: 6
Inside: 6

Can any one explain?

Bharath Kumar
  • 820
  • 1
  • 9
  • 21
  • `setTimeout(function(i){ console.log('Inside: ',i); }, 1000, i);` Use the 3rd parameter of __setTimeout__ – Rajaprabhu Aravindasamy Jul 28 '16 at 14:45
  • Never put a setTimeout inside a for loop. You use setTimeout based on recursive logic. And stop calling it when you're logic dictates the end of setTimeout looping. – ManoDestra Jul 28 '16 at 14:50

0 Answers0