Event loop mechanism:

The execution process is as follows: the JavaScript engine first removes the first task from the MacroTask Queue, then removes all tasks from the MicroTask queue and executes them in sequence. Then remove the macroTask queue from the macroTask queue, and remove the macroTask queue from the macroTask queue. The loop repeats until both queues run out of tasks.

Explanation: When the code starts executing, all of this code is pulled from the MacroTask Queue to execute. SetTimeout is then encountered, which is then added to the MacroTask Queue, and promise.then, which is added to another queue, the MicroTask Queue. Once the execution Context stack is complete, the next step is to fetch tasks from the MicroTask Queue. Thus the callback to promise.then is executed before setTimeout.

When setTimeout is pushed into the task queue:

Let’s take a look at some code

 setTimeout(function () {
   console.log('abc')
 }, 1000)
 for (var i = 0; i <= 800000000; i++) {
    if (i == 800000000) {
       console.log(i)
    }
 }
Copy the code

If only the following for loop was executed, it would output 800000000 in about 3.4 seconds. When setTimeout is added above, it is found that 800000000 is output in about 3.4 seconds, followed by ABC immediately. Change setTimeout from 1000 to 2000 or 3000 and it will output immediately. However, when changed to 9000, it was found that it took about 6 seconds to output. This shows that the function in setTimeout will start timing when setTimeout is executed. When the timing is completed, the function will enter the task queue. When the execution stack is finished, the task queue will start to execute.