简体   繁体   中英

Why does setTimeout in a while loop increment in order?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM