for (var i=1; i<=5; i++) { setTimeout( function timer(){ console.log( i ); }, i*1000 ); }
At second glance, it does make sense. The timer() function is invoked after the waiting period (i*1000). By the time it starts to execute, the for loop has long finished. And at this point of time, i = 6.
So how to fix it?
By wrapping the setTimeout() with a function makes the variable j local to the enclosing function.
for (var i=1; i<=5; i++) { (function(){ var j = i; setTimeout( function timer(){ console.log(j); }, i*1000 ); })(); }
for (var i=1; i<=5; i++) { (function(j){ setTimeout( function timer(){ console.log(j); }, i*1000 ); })(i); }
for (let i=1; i<=5; i++) { setTimeout( function timer(){ console.log(i); }, i*1000 ); }
No comments:
Post a Comment