Answer the question
In order to leave comments, you need to log in
Why does JS code work like this?
Good afternoon. There is a typical interview question:
What will be the result of executing the following code:
for (var i = 0; i < 10; i++) {
setTimeout(function () {
console.log(i);
}, 0);
}
Answer the question
In order to leave comments, you need to log in
https://developer.mozilla.org/en-US/docs/Web/JavaS...
Zero delay doesn't actually mean the call back will fire-off after zero milliseconds. Calling setTimeout with a delay of 0 (zero) milliseconds doesn't execute the callback function after the given interval. The execution depends on the number of waiting tasks in the queue.
A reference to `i` will get into the closure, and the timer function will work after the cycle has passed and i at that moment will already be 10.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question