Who can explain why the number 10 is displayed 10 times, and not in order. I know that the timer is first added to the queue, and then I don’t know what is going on.

for (var i=0; i<10; i++) { setTimeout('alert(i)', 1000); } 

Reported as a duplicate by participants Duck Learns to Hide , Alexey Shimansky , Grundy javascript Dec 17 '16 at 20:32 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • one
    See the scope in js Young Padawan. This question was asked on this site 100,500 times, and I'll even look for where they have already been answered. - Duck Learns to Take Cover
  • Actually follow the link above and read the detailed answer to almost the exact same question. - Duck Learns to Take Cover
  • Don't be sad, @DivMan, I'll help you out :) for (var i = 0; i < 10; i++) { setTimeout('alert(' + i + ')', 1000); } for (var i = 0; i < 10; i++) { setTimeout('alert(' + i + ')', 1000); } - Igor

1 answer 1

The whole point is that the functions added to setTimeout fall into the end of the execution queue. First, the loop body and all logic will be executed and only at the end the alert (i) function will be called. It is natural that by that time the cycle will be completed and the variable i will contain 10

I recommend reading this article.