In the canonical example* to learn closures, we are presented with the following:
Let’s say we would like to display numbers 1 to 5 at once sequentially. We can accomplish this easily with a simple for loop:
for (var i = 1; i <= 5; i++) {
console.log(i); // outputs 1 2 3 4 5
}
The code block above should output 1 2 3 4 5 in the console. But what if we want to delay the output and have each number display 1 second apart from each other consecutively? The setTimeout() function seems like the perfect candidate for the job:
for (var i = 1; i <= 5; i++) {
setTimeout(function() { console.log(i); }, 1000*i); //outputs 6 6 6 6 6
}
The above code seems like the obvious answer. We put console.log(i) within an anonymous function inside a setTimeout() function, and set each setTimeout() to be delayed 1 to 5 seconds (1000 x 1, 1000 x 2…) respectively. However, as soon as we run that codes, we know something is wrong. The numbers are each outputting to console 1 second after another consecutively, but they are all 6s. So we now have 6 6 6 6 6 as the end result.
From my understanding of loops...
We set the iterator, in our case: var i = whatever number you'd like;
We set the condition: i <= 5;
We set the incrimentor: i++
We then we wrap what we want to execute in a set of {}
in our case:
{
setTimeout(function() {
console.log(i);
}, 1000 * i);
}
But I thought the sequence which followed was:
- Condition gets evaluated to see if block will fire
- Code block gets executed
- Incriminator fires
- Variable is assigned to the new value (from the incriminator)
- Goes back to check condition will fire or loop will end
* I referenced this blog for the loop and insights....