The flow of JavaScript execution in the browser and the flow in Node.js are based on Event loops.

After each macro task, the engine immediately executes all tasks in the microtask queue, and then performs other macro tasks, or renders, or other operations. — – JavaScript. Info

classification

  • Macro task

The entire code script, setTimeout, setInterval, setImmediate, requestAnimationFrame, IO, UI interaction events

  • Micro tasks

Promise(.then/catch/finally), process.nexttick, MutaionObserver, queueMicrotask(func) (this method allows funC to be executed in microtask queues)

Event loop algorithm

  1. Dequeue from a macro task queue (such as “script”) and execute the earliest task.
  2. Perform all microtasks:
  • When the microtask queue is not empty:
    • Dequeue and perform the earliest microtask.
  1. If there are changes, render them.
  2. If the macro task queue is empty, sleep until the macro task appears.
  3. Go to Step 1.

conclusion

  1. There is a difference between synchronous and asynchronous code. When the JS engine encounters synchronous code, it will put it into the main thread to execute first.
  2. When asynchronous code is encountered, it is put into an asynchronous task queue for execution. Asynchronous tasks are divided into micro tasks and macro tasks, which are placed in different queues.
  3. When the code in the main process finishes executing, the code in the asynchronous task queue is put into the main thread for execution. The microtask queue will be placed in the main thread for execution before the macro task queue. If new microtasks are generated during the execution of the microtask entering the main thread, the microtasks will continue to be placed in the main thread for execution after the execution of the main thread until the microtask queue is empty.
  4. Tasks in the macro task queue enter the main process for execution.
  5. Proceed to step 2, and the process repeats itself, known as the Event Loop.

reference

  • Event loops: microtasks and macro tasks
  • Micro tasks
  • SetTimeout +Promise+Async output order
  • This time, thoroughly understand the JavaScript execution mechanism