Why is the alert (i), in seTimeout out of order in closures?

A classic closure question

for (var i = 1; i <= 5; iPP) {
   (function a(i) {
       setTimeout(function() {
           alert(i);
       }, 1000);
   })(i);
}

in theory, it should pop up 1, 2, 3, 4, 5, but the actual pop-up is out of order. The conversion of
to console.log (i) is 1, 2, 3, 4, 5.
Why is this?

Mar.02,2021

because alert will block the process
the first pop-up must be 1 . If you don't click OK when popping up, it will be blocked all the time, and all subsequent code and callback functions will not be executed.

after the execution of Synchronize code is completed, five timers are generated. When pop-up 1 waits for you to click OK, all the subsequent timers are ready, so they are out of order

.

and the console function does not block, so the

is executed sequentially.
Menu