0

This is a javascript code snippet. I don't understand how only '5' is being printed at the output. That too only once.

Here is the code :

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

output - 5.

Shouldn't 1,2,3,4 be the output?

Shreyash S Sarnayak
  • 2,309
  • 19
  • 23

1 Answers1

0

First of all it doesn't print 5 once but 5 times each at an interval of 1 sec

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

It happens because the timeout function callbacks are all running well after the completion of the loop. In fact, as timers go, even if it was setTimeout(.., 0) on each iteration, all those function callbacks would still run strictly after the completion of the loop, that's why 5 was reflected as that will be the last value of i in the loop. Each of the timer handler functions will share the same variable "i"

If you want to seperate value each time. you can call a separate function in it passing i as a value and hence each will have a different value

function checkTimeout(i) {
      setTimeout(function() { console.log(i); }, 1000*i);
    }
    
    for (var i = 1; i <= 5; ++i) {
      checkTimeout(i);
    }
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400