0
  • I am new to js
  • I thought below code will output 0,1,2,3,4,5,6,7,8,9 with a gap of 10 ms.
  • but it's not printing like that it's printing 10 ten times.
  • is it due to set a timeout or something else?
  • can you guys tell me why it's happening...it will help me so much with understanding js
for( var i=0; i< 10; i++) {
    setTimeout(function(){ 
        console.log(i);
    }, 10);

}
mu is too short
  • 426,620
  • 70
  • 833
  • 800

1 Answers1

1

It's because of closure, you should do something like that

for( var i=0; i< 10; i++) { 
    (function(j){
       setTimeout(function(){ console.log(j); }, 10);
    }(i));
}

This is basic javascript closure, you can read more here How do JavaScript closures work?

The problem is that the for loop finishes first, so at the end, i will equal 10. After that, the setTimeout functions will get called and when they check the value of i, they'll find it equal to the last value from the for loop which 10. What I did is called an IIFE (Immediately Invoked Function Expression) which creates a new variable for the scope of the setTimeout function, so when the timeout comes, it finds its own variable that hasn't changed.

Community
  • 1
  • 1
Ayman El Temsahi
  • 2,600
  • 2
  • 17
  • 27
  • thanks for your reply...here I did not assign value for j but how its printing for j...I read the link which you provided but still I am not getting...can you tell in simple terms...sorry :( –  Apr 03 '17 at 01:59