2

I have 2 simple code snippet about for loop involving let and var separately. First code which has a variable declared with let

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

so it will show o/p like this

0123456789 

but if I replace let with var like this

 for (var i = 0; i < 10; i++) {
       setTimeout(function() {
          console.log(i);
       }, 1000);
    }
it will print 10 for ten times. 

I know it is something related to function level scope and block-level scope, but want to clearly understand step by step process of execution.

Thanks in advance.

Hien Nguyen
  • 24,551
  • 7
  • 52
  • 62
Alok Ranjan
  • 967
  • 10
  • 10

1 Answers1

2

The reason why you are only printing 9 is that the callback function is executed after the loop is done. Which means that i is 9.

You can:

If you are trying to print 1 - 10 after 1 sec, you can loop in the callback function. Like:

setTimeout(function() {
  for (var i = 0; i < 10; i++) {       //Put the loop inside the setTimeout db function.
    console.log(i);
  }
}, 1000);

If you are trying to print every one sec, you can pass the i as the 3rd parameter on setTimeout

for (var i = 0; i < 10; i++) {
  setTimeout(function(o) {           //Receive it on variale o
    console.log(o);
  }, 1000 * i, i);                   //Pass the i as third parameter
}

Doc: setTimeout

Eddie
  • 26,593
  • 6
  • 36
  • 58