0

The example cited leaves me cold. It does not answer the question.

The intention of the code is to output numbers from 0 to 4 in the console every second. However, it outputs the number 5 five times.

The reason is that after five iterations, the value of the i variable is 5. And the five instances of the callback function passed to the setTimeOut() function refers to the same variable i with the final value 5.

Could someone explain this better? Why isn't the settimeout function called each time i changes? Why is the timeout function called 5 times with the same value for i?

 for (var i = 0; i < 5; i++) {
    setTimeout(function () {
        console.log(i);
    }, 1000);
}
DCR
  • 14,737
  • 12
  • 52
  • 115
  • 1
    I don't think one could put it much better than "*the five instances of the callback function passed to the `setTimeOut()` calls refer to the **same** variable `i` which holds the final value 5.*" What in particular do you not understand about this? – Bergi Jul 14 '20 at 20:08
  • 1
    "*Why isn't the settimeout function called each time i changes?*" `setTimeout` is called 5 times, and `i` has a different value during each iteration. "*Why is the timeout function called 5 times with the same value for i?*" - the callback function is not called *with* a value for `i` at all. It is called *when* the `i` variable already has the value 5. – Bergi Jul 14 '20 at 20:10
  • it doesn't make any sense. the answer is not explaining what exactly is happening – DCR Jul 14 '20 at 20:10
  • The calls to setTimeout are asynchronous not synchronous. You're putting 5 calls to setTimeout on the stack in succession. They run once (giving you "1" output 5 times) then the code finishes. – Adam Jul 14 '20 at 20:10
  • if it's placing 5 calls to the stack doesn't it place the first call when i = 0 and the second call when i=1..... does it then wait 1000 and then execute the call back when i = 5? if that's true, then how about settimeout((function(){console.log(i),0);}? – DCR Jul 14 '20 at 20:14
  • Placing a request to run the function 5 times happens independently of i changing. It's 5 calls to a function that logs i. It just so happens that when those functions are executed, i is already 5. Changing `var` to `let` in your for loop scopes i differently so when it comes time to execute those 5 calls, each has its own different value for i. – James Jul 14 '20 at 20:31

0 Answers0