Why does setTimeout in a while loop increment in order?

Viewed 305

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++;
}
2 Answers

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...

  • 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()
Related