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++;
}
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...
i = 0. while loop, it'll be incremented to 1, 2, 3, 4 and stop when it reaches 5.setTimeout function is asynchronous, so even with a delay of 0, it'll be called after the current thread finishes (the while loop).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()