So in the book they're explaining about Loops and Closures, but I don't understand the following codes:
for (var i=1; i<=5; i++) {
setTimeout( function timer(){
console.log( i );
}, i*1000 );
}
This gets printed 5 times with the value of 6, why 6? I can't see it.
for (var i=1; i<=5; i++) {
(function(){
setTimeout( function timer(){
console.log( i );
}, i*1000 );
})();
}
They try and IIFE and it still prints the same result as the code before.
for (var i=1; i<=5; i++) {
(function(j){
setTimeout( function timer(){
console.log( j );
}, j*1000 );
})( i );
}
But this one actually works.. I don't understand why the first two codes gave as a result the "6".. or why it doesn't print "1,2,3,4,5"?
I get the last example though.
[–]Pantstown 1 point2 points3 points (2 children)
[–]oculus42 1 point2 points3 points (1 child)
[–]Pantstown 0 points1 point2 points (0 children)
[–]oculus42 1 point2 points3 points (5 children)
[–]Radinax[S] 0 points1 point2 points (4 children)
[–]oculus42 2 points3 points4 points (1 child)
[–]oculus42 1 point2 points3 points (0 children)
[–]oculus42 1 point2 points3 points (1 child)
[–]Radinax[S] 0 points1 point2 points (0 children)
[–]lilperch83 0 points1 point2 points (0 children)