for ( var i = 0; i < 5; i++ ) {
setTimeout(function() {
alert( i );
}, i * 100 );
}
I took the above example from the internet to understand closures. But I could not understand why it alerts value 5 for 5 times. Instead of alerting 1,2 3,4 ,5.
But the following way can be done. Can someone explain why. I am new to JavaScript so please provide some elaborate answers.
var createFunction = function( i ) {
return function() {
alert( i );
};
};
for ( var i = 0; i < 5; i++ ) {
setTimeout( createFunction( i ), i * 100 );
}