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!

6
  • 2
    Your invoking console.log(i) immediately inside the loop.. Commented Jul 19, 2018 at 12:46
  • 1
    As @Keith told you, you invoke the function, so it is called. No mystery here. Commented Jul 19, 2018 at 12:47
  • @Keith could you please describe it more? Commented Jan 30, 2020 at 9: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, Commented Mar 11, 2020 at 5:50
  • 1
    Hi, refer to this, this stackoverflow.com/a/60630117/4248767 Commented Mar 11, 2020 at 6:13

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.