D
D
dusun2018-02-07 13:30:43
JavaScript
dusun, 2018-02-07 13:30:43

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

Will output 10 times the number 10. I completely forgot why this works? Can you remind me? Thank you.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
K
kzoper, 2018-02-07
@kzoper

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.

R
RidgeA, 2018-02-07
@RidgeA

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.

T
tyzberd, 2018-02-07
@tyzberd

https://www.youtube.com/watch?v=8cV4ZvHXQL4

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question