QWhat does the following code produce?
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 1);
}
Question Info
Choose the Best Option
Click any option to instantly check if you're correct.
Explanation
In this code, we are using a for loop to iterate over a range of values, and we are using the setTimeout() function to log the value of i to the console after a delay of 1 millisecond.
However, the setTimeout() function runs asynchronously, which means that it does not block the rest of the code from executing.
This means that the for loop will complete immediately, and the value of i will be incremented to 3.
Since the setTimeout() function has a delay of 1 millisecond, it will not run until after the for loop has completed.
By the time the setTimeout() function runs, the value of i will already be 3, so it will log 3 to the console three times.
Share This Question
Challenge a friend or share with your study group.