5

can someone help me understanding why this code:

for (var i =0; i < 2; i++) {
  setTimeout(console.log(i), 0);
}
console.log("aaa");

Will write:

0
1
aaa

But that code:

for (var i =0; i < 2; i++) {
  setTimeout(function(){console.log(i)}, 0);
}
console.log("aaa");

Will wirte that:

aaa
2
2

Note that I understand how the second vers. work, I don't get why the first one make it differnt.

Thanks!

TessavWalstijn
  • 1,698
  • 1
  • 19
  • 36
shr7
  • 163
  • 1
  • 2
  • 6
  • 2
    Your invoking `console.log(i)` immediately inside the loop.. – Keith Jul 19 '18 at 12:46
  • 1
    As @Keith told you, you invoke the function, so it is called. No mystery here. – sjahan Jul 19 '18 at 12:47
  • @Keith could you please describe it more? – Vikas Chauhan Jan 30 '20 at 09:46
  • 1
    Hi All,I think he is asking that directly calling a console.log() in setTimeout() instead of calling inside a callback function in setTimeout behave differently, He is asking what is the reason for that, – Nuwa Mar 11 '20 at 05:50
  • 1
    Hi, refer to this, this https://stackoverflow.com/a/60630117/4248767 – Nuwa Mar 11 '20 at 06:13
  • Newa is right here... see the link he posted. This is because of closure, because of the difference in scheduling the two calls. In the second example, by the time both the functions get to run, the value of i is 2. – Serge Oct 28 '21 at 19:11

0 Answers0