Closed
Description
https://github.com/jquery/learn.jquery.com/blob/master/page/javascript-101/closures.md
// Each function executed within the loop will reference
// the last value stored in i (5).
// This won't behave as we want it to - every 100 milliseconds, 5 will alert
for ( var i = 0; i < 5; i++ ) {
setTimeout(function() {
alert( i );
}, i * 100 );
}
In Javascript-101 in the closures chapter, the setTimeout
method is used before it's introduced what that is. This example would be easier to understand if it used something different that had already been introduced in previous chapters.
I haven't been able to think of an alternative example that exhibits the behavior that the existing example does (but this likely stems from being in the process of learning js myself).