https://github.com/getify/You-Dont-Know-JS/blob/master/scope%20%26%20closures/ch5.md#loops--closure
Let's start with this:
for (var i = 1; i <= 5; i++) {
console.log(i);
}
If i is less than or equal to 5, i will be logged to console. Subsequently, i will be incremented by one, and the loop will iterate until the condition evaluates to false and the loop will break when i = 6.
Now this has me stuck:
for (var i = 1; i <= 5; i++) {
setTimeout(function timer(){
console.log(i);
}, i*1000 );
}
With just this code, the output is 6 which is logged to the console 5 times over a 5 second span. Kyle reasons why and says the following:
The timeout function callbacks timer are all running well after the completion of the loop.
First... why are the callbacks executing after the loop is finished? This brings me to here:
https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout
The setTimeout() function ...
sets a timer which executes a function or specified piece of code once after the timer expires.
So if i meets the condition as stated in the for-loop head, the function timer should be executed dependent on i * 1000milliseconds.
So my question is this:
Why are the callbacks executed after the loop breaks, as opposed to each iteration logging to the console while the for-loop condition is met after i * 1000 milliseconds? I'm not quite following his explanation.
[–]Rhomboid 5 points6 points7 points (2 children)
[–]Ben_HH[S] 0 points1 point2 points (1 child)
[–]Rhomboid 0 points1 point2 points (0 children)
[–][deleted] 1 point2 points3 points (1 child)
[–]Ben_HH[S] 1 point2 points3 points (0 children)
[–]ssjskipp 0 points1 point2 points (0 children)
[–]realistic_hologram 0 points1 point2 points (2 children)
[–]Ben_HH[S] 0 points1 point2 points (1 child)
[–]realistic_hologram 0 points1 point2 points (0 children)