0

Following code only prints 5

for(var x=0; x<5; x++) {
    setTimeout(()=>console.log(x), 0)
}

And following code prints 0,1,2,3,4

for(let x=0; x<5; x++) {
    setTimeout(()=>console.log(x), 0)
}

What way setTimeout is behaving? Second argument to setTimeout is 0, so it should immediately execute the callback, which is the first argument. If the second argument were some positive number, say 10, then I understand by the callback is called, x would have reached its final value and that also I think should have been 4 in place of 5.

Subhendu Mahanta
  • 961
  • 1
  • 18
  • 44
  • @trincot, I read the duplicate question before posting the question, but could not understand setTimeout behavior here. And I expected the var version of the code, to log 5 times to the console, it is doing so only once. – Subhendu Mahanta Nov 10 '16 at 00:57
  • @Liam in the duplicate question, it has been explained with click handler code, I understood that. But I have not understood my case.Do not know what I am missing. – Subhendu Mahanta Nov 10 '16 at 00:59

0 Answers0