helpermethod
helpermethod

Reputation: 62155

Why is count correctly incremented

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 );
}

Upvotes: 4

Views: 71

Answers (2)

ndugger
ndugger

Reputation: 7531

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);
};

Upvotes: 2

Pointy
Pointy

Reputation: 413712

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.

Upvotes: 10

Related Questions