Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is count correctly incremented

Tags:

javascript

Consider this simple example:

var count = 0;
for (var i = 0; i < 4; i++ ) {
    setTimeout(function() {
      console.log(i, count++);
    }, i * 200);
}

which outputs the following

4 0
4 1
4 2
4 3

I would guess that i always resolves to 4 because the setTimeout callback closes over the variable I but I can't figure out why the same doesn't hold true for count?

var count = 0;
for (var i = 0; i < 4; i++ ) {
  setTimeout(function() {
    console.log(i, count++);
  }, i * 2000 );
}
like image 461
helpermethod Avatar asked Dec 14 '22 17:12

helpermethod


2 Answers

The variable i is incremented by your for loop, and ends up with the value 4 before any of the timeout handlers run. The variable count, on the other hand, is only incremented inside the timeout handlers. When the first timeout handler fires, count will still be 0.

like image 114
Pointy Avatar answered Dec 26 '22 17:12

Pointy


As the lads before me said, It's because the loop completes before the timeout is activated.

One way around this would be to put your timeout in a different function, and pass the i to it from within the loop. This ensures that for each iteration, the function is passed the correct i

This is also why count is set to the expected value; it lies outside of the loop's scope.

for (var i = 0; i < 4; i++) {
    doSomething(i);
};
function doSomething(i) {
    setTimeout(function() {
        console.log(i);
    }, i * 2000);
};
like image 21
ndugger Avatar answered Dec 26 '22 16:12

ndugger