0

I'm confused why the option 1 prints out '6', 5 times, whereas the option 2 prints out 0,1,2,3,4,5. Shouldn't the first one print out like the option 2?

Option 1:

for (var i = 0 ; i <= 5; i++) {
    setTimeout(function() {
        console.log(i);
    });
}

Option 2:

for (var i = 0 ; i <= 5; i++) {
    doThis(function() {
        console.log(i);
    });
}
function doThis(a) {
    a();
}
jcubic
  • 61,973
  • 54
  • 229
  • 402
  • 3
    Does the answer to this explain it? http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – epascarello Jan 19 '16 at 13:27
  • 2
    Basically because the option 1 is async. A way to avoid this is wrapping it with `(function(i){ /* code */ })(i);` – Francisco Presencia Jan 19 '16 at 13:29
  • No, I'm still confused. I'm just replacing setTimeout with a another function, but it's producing a different result. – sassyjsprogrammer Jan 19 '16 at 13:35
  • @FranciscoPresencia can you dig little deeper into what async really means? – sassyjsprogrammer Jan 19 '16 at 13:36
  • it's because `setTimeout` is executed after the for loop has finished and the value of `i` is `5` then. – jcubic Jan 19 '16 at 13:36
  • @jcubic why is the setTimeout executed after the for loop? – sassyjsprogrammer Jan 19 '16 at 13:38
  • It's because setTimeout add function to the queue that is executed after current task is finished and the current task is for loop so it execute after it's finish. – jcubic Jan 19 '16 at 13:40
  • Because [`setTimeout`](https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setTimeout) was designed to do that. – Teemu Jan 19 '16 at 13:41
  • Check this video What the heck is the event loop anyway? https://www.youtube.com/watch?v=8aGhZQkoFbQ – jcubic Jan 19 '16 at 13:41
  • awesome thanks! here's a more detailed explanation: http://brackets.clementng.me/post/24150213014/example-of-a-javascript-closure-settimeout-inside – sassyjsprogrammer Jan 19 '16 at 13:42
  • I think I'm late to the party, it is one of the main differences of javascript with other languages (and one of the reasons why it's so powerful). Please read about the topic "asynchronous javascript", since it's a big topic and difficult to explain in a comment. – Francisco Presencia Jan 19 '16 at 13:48

0 Answers0