4

I had a question at the interview. I just don't get why this prints 5 6 7 8 9...

let i = 0;

while (i < 5) {
  setTimeout(() => {
    console.log(i++);
  }, 0);
  i++;
}
Alireza
  • 2,319
  • 2
  • 23
  • 35
doglabel
  • 61
  • 8
  • 2
    The entire while loop runs before the first timeout fires. That’s the nature of async javascript. Your code runs to completion before async callbacks start. – Mark Dec 28 '18 at 17:54
  • When using setTimeout you are adding a reference to i so i gets incremented to 5 before it starts calling the setTimeout() – Ryan Wilson Dec 28 '18 at 17:54
  • You can read more about Event Loop in JS in order to understand this. I recommend this video: https://www.youtube.com/watch?v=8aGhZQkoFbQ – L. Figueredo Dec 28 '18 at 17:55

2 Answers2

1

It is because of the setTimeout () function. Even though it delays 0 seconds. This will lower it's priority in processor. All 5 actions inside setTimeout functions will run after the while loop. Since at the end of it i is 5. So it logs and increments after that...

Sachith Rukshan
  • 340
  • 6
  • 24
  • 1
    `This will lower it's priority in processor.` what? no it doesn't. No matter what interval is specified, the enqueued action will not execute until the main execution context has yielded control back to the browser. If the interval expires before that happens, it will wait, and that is what happens here. –  Dec 28 '18 at 18:01
  • Thanks. Will check it. – Sachith Rukshan Dec 28 '18 at 18:20
1
  • Your code starts with i = 0.
  • When it enters the while loop, it'll be incremented to 1, 2, 3, 4 and stop when it reaches 5.
  • The setTimeout function is asynchronous, so even with a delay of 0, it'll be called after the current thread finishes (the while loop).
  • Since i was at 5 when the while loop ended, the setTimeout functions will pick it up from there, outputting its value and incrementing it by one on each subsequent console.log()
M -
  • 26,908
  • 11
  • 49
  • 81