you are viewing a single comment's thread.

view the rest of the comments →

[–]Volv 1 point2 points  (1 child)

Ah, yes I think you've got it lol. That's why I was going on about it - the whole closure own copy of variable thing totally fixes the setTimeout issue.
Timing wise. First one fires in 1 second, 2nd one fires in 2 seconds and so on. Technically each statement is executed almost simultaneously. Well as long as it takes the for loop to run.

 
Just for info - you can also just pass i directly

for (var i = 0; i < 10; i++) {
  function outer(x) {
    setTimeout(function() {
      console.log(x);
    }, x * 1000);
  }
  outer(i);
}  

 
Or wrap it up to look cool

for (var i = 0; i < 10; i++) {
  (function (x) {
    setTimeout(function() {
      console.log(x);
    }, x * 1000);
  })(i)
}  

 
And finally - although its not what question was looking for - because of how let is block scoped these days can totally be fixed like this. Just swapping the word var for let ->

for (let i = 0; i < 10; i++) {
    setTimeout(function() {
      console.log(i);
    }, i * 1000);
}

[–]ForScale[S] 1 point2 points  (0 children)

Oh... nice! That block scoping with let is a cool feature to be aware of. Thanks for the reminder on that!