How does hoisting explain this behavior?
for(var i = 0; i < 4; i++) {
setTimeout(function() {
alert("i is: " + i);
}, i * 200);
}
The output of this is 4, 4, 4, 4.
This is used as a dangerous example of hoisting often in literature. It makes sense that the latter outputs may be 4 since the i variable is bound to function scope and as such is shared between all calls and by the time they execute i will be 4 having finished the for loop. However, the initial call specifies a timeout of 0 * 200 or 0 and as such I feel this should execute immediately while i is still less than 4. What causes all the output from this function to be 4's?