JS event loop mechanism in browser

table of Contents

  • Event loop mechanism
  • Macro tasks and micro tasks
  • Case Analysis
  • reference

1. Event loop mechanism

Browser event loop mechanism

Browser execution of JS code can be roughly divided into three steps, and the reciprocation of these three steps constitutes the JS event loop mechanism (see figure).

The first step: execute the JS whole code or callback function (that is, macro task) in the main thread (JS engine thread), store the object in the heap during execution, and add the basic types and functions to the stack (stack ), The heap will be released or the stack will be exited after execution. After the execution of this macro task, it will determine whether the micro task queue (microtask queue) is empty. If it is not empty, it will take out all the micro tasks in sequence and execute them. If any Web APIs are triggered during this process, the second step will be performed.

The second step: call the Web API and add the callback function to the event queue when appropriate. For example, implemented setTimeout(callback1, 1000), it will create a timer, and in another thread (the browser periodically trigger the thread) which monitor the timer has expired, wait until after the timer expires, the corresponding callback will callback1join the event callback stack.

Step 3: After the execution of the microtask in the first step is completed, it will determine whether the event callback stack (event queue) is empty. If it is not empty, it will take out and execute the callback function that first enters the queue, the execution process is like the first step. If it is empty, it will wait or suspend the main thread as appropriate.


Supplementary note: The core of the browser is multi-threaded, and the resident threads are the browser GUI rendering thread, JavaScript engine thread, browser timing trigger thread, browser event trigger thread, and browser http asynchronous request thread.


2. Macro tasks and micro tasks

Macrotasks: script (overall code), setTimeout / setInterval, I / O, UI rendering, etc.

Microtasks: Promise, MutationObserver, etc.


JS code execution process-schematic diagram of the execution of macro tasks and micro tasks:

Schematic diagram of the execution of macro tasks and micro tasks

As shown in the figure, it can be seen that during the execution of JS, a macro task is executed first, and then the corresponding micro task generated by this macro task is executed. After the execution is completed, the subsequent macro task is executed again and again.


3. Case analysis

Use a browser: Chrome Version 80.0.3987.163

First group:

Compare setTimeout and Promise

console.log('start')

setTimeout(() => {
  console.log('setTimeout')
}, 0);

Promise.resolve().then(() => {
  console.log('microtask: promise')
})

console.log('end')

result:

Compare setTimeout and Promise

analysis:

To analyze the JS event loop mechanism. First of all, the script (overall code) is a macro task. After execution, it will output "start" and "end" successively, and then execute the micro task generated in this process, that is, the callback in promis.then, output "microtask: promise" ; In this process, setTimeout in Web API is also called, a timer will be created, and the callback will be added to the event callback stack after expiration; then execute the callback (the second macro task), and output "setTimeout". Consistent with the output of the browser operation, as expected.


Second Group:

Comparison of the execution order of macro tasks and micro tasks

function func1() {
  console.log('func1')
  Promise.resolve().then(() => {
    console.log('microtask.promise1')
  })
}

function func2() {
  console.log('func2')
  Promise.resolve().then(() => {
    console.log('microtask.promise2')
  })
}

function main() {
  func1()
  func2()
  setTimeout(func1, 0);
  setTimeout(func2, 0);
}

main()

result:

Comparison of the execution order of macro tasks and micro tasks

analysis:

It can be seen from the output results that when a macro task is executed, it will then execute all corresponding micro tasks. After the execution is completed, the subsequent macro tasks will be executed again and again, in accordance with expectations.


4. Reference

Concurrency model and event loop

Javascript event loop

JavaScript Event Loop Explained

HTML series: macrotask and microtask

【Translation】 Promises / A + specifications

Guess you like

Origin www.cnblogs.com/forcheng/p/12746392.html