0

I'm a novice and pretty confused with the following code.

for (var i=1; i<=5; i++) {
    console.log('ooo');
    setTimeout( function timer(){
        console.log( i );
    }, i*1000 );
}

The output of this code was something like this:

ooo
ooo
ooo
ooo
ooo
6
6
6
6
6

Thanks in advance in explaining me this code.

shahzaibkhalid
  • 117
  • 2
  • 8

2 Answers2

0
for (var i=1; i<=5; i++) {
    console.log('ooo');
    setTimeout( function timer(){
        console.log( i );
    }, i*1000 );
}

in this code when the setTimeout() is called the for loop would have finished and each function would refer to the same value of i i.e 6

function closure(i){
    setTimeout( function timer(){
        console.log( i );
    }, i*1000 );
}

for (var i=1; i<=5; i++) {
    console.log('ooo');
    closure(i);
}

this would print i = 1 to 5 since the functions can see only the corresponding value of i in it

marvel308
  • 10,288
  • 1
  • 21
  • 32
  • If the for-loop has already finished prior to the calling of `setTimeout` function, then shouldn't it be executed just once? – shahzaibkhalid Sep 01 '17 at 10:00
  • @shahzaibkhalid After completion of every iteration settimeout function will be stacked in stack. Once the setimeout waiting time over browser execute from stack(at that moment value of i will be 6). – messi Sep 01 '17 at 10:02
  • The setTimeout functions is an asynchronous function and would be waiting in the job queue waiting for the event loop to pick it up, When the event loop picks it up it would refer the i = 6 – marvel308 Sep 01 '17 at 10:02
0

The correct result should be like below You should think as below instruction 1 code will console 000 <= 5 times i is incremented by your for a loop. By the time the timer function is executed the first time, I have been incremented and is now valued to 127 then 6.

16:57:40.946  ooo
16:57:40.946  ooo
16:57:40.946  ooo
16:57:40.947  ooo
16:57:40.947  ooo
16:57:40.947  127
16:57:41.949  6
16:57:42.947  6
16:57:43.951  6
16:57:44.947  6
16:57:45.950  6
DMS-KH
  • 2,669
  • 8
  • 43
  • 73