Why is the score correctly increasing

Consider this simple example:

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

which displays the following

4 0
4 1
4 2
4 3

I would suggest that it ialways resolves to 4, because the setTimeout callback closes on variable I, but I cannot figure out why the same is not true for count?

var count = 0;
for (var i = 0; i < 4; i++ ) {
  setTimeout(function() {
    console.log(i, count++);
  }, i * 2000 );
}
Run code
+4
source share
2 answers

The variable is iincremented by your loop forand ends with a value 4until any of the timeout handlers are started. On the other hand, the variable countonly increases in timeout handlers. When the first timeout handler fires, it countstill will 0.

+10
source

: " , , - ".

, - i . , i

count ; .

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

Source: https://habr.com/ru/post/1570184/


All Articles