One sentence explanation

Js main thread is a single thread of operation, main line first synchronization code, with asynchronous operations such as ajax requests, timer need to perform after a period of time in the event, and then she gave it to other threads, such as the requesting thread, timing trigger thread, satisfy the conditions and then into the task queue, after the main thread to perform the task, go to task queue lira quests, In accordance with the first in first out principle of execution, so cycle; The task queue is divided into macro task queue and micro task queue. After the execution of a macro task, it will check whether there are micro tasks. After the execution of all micro tasks, the page will be updated and rendered, and then the next macro task will be executed.

Question and answer

1. Why is JS single threaded?

  • Prevent confusion when operating on the same DOM at the same time.
  • “JS is single threaded “just means that there is only one main thread running JS, not the entire runtime environment is single threaded.

2. How to implement asynchronous JS single thread?

  • JS asynchronous implementation depends on the browser’s multithreading, when the asynchronous API, the task will be given to the corresponding thread, when the asynchronous API meets the callback conditions, the corresponding thread through the event trigger thread will put the event into the task queue, and then the main thread from the task queue to continue to execute the event.
  • JS engine thread and GUI thread are mutually exclusive, one execution does not execute the other, if JS runs for a long time, GUI thread cannot execute, the whole page will feel dead.

3. Why microtasks?

  • Microtask is to solve the problems of efficiency and real-time, and to deal with high-priority tasks.

4. What are the common macro and micro tasks?

  • Macrotask: Script, setTimeout, setInterval, setImmediate, I/O
  • Microtask: Promise, MutaionObserver, process.nexttick (Node)

5. When does the browser render?

  • Render once after executing a macro task and all current microtasks;
  • However, not every round of the Event Loop updates the render, depending on whether the DOM has been modified and whether the browser feels the need to present the new state to the user immediately at this point. If multiple DOM changes are made in the span of a frame (the time is uncertain because the browser’s frames per second always fluctuate; 16.7ms is just an inaccurate estimate), the browser might stack the changes and draw only once.

6. How is the event loop different from the Node environment?

In the Browser and Node environment, the execution timing of the MicroTask queue is different:

  • On the browser side, microTask is executed after macroTask in the event loop completes execution.
  • Node version >=11, same as browser;
  • Node version <11, the microTask is executed between each phase of the event cycle, that is, after the execution of a phase, the microTask queue will be executed.

Because the timer insertion time is different, the execution result of the same code will be different, as follows:

setTimeout(()=>{
    console.log('timer1')
    Promise.resolve().then(function() {
        console.log('promise1')
    })
}, 0)
setTimeout(()=>{
    console.log('timer2')
    Promise.resolve().then(function() {
        console.log('promise2')
    })
}, 0)
Copy the code

The Node side is divided into six stages,

  • Timers stage: This stage performs the callback of timer (setTimeout, setInterval)
  • I/O Callbacks phase: Handles some of the few unexecuted I/O callbacks from the previous cycle
  • Idle, prepare: Used only internally
  • Poll phase: Fetch new I/O events, where node will block under appropriate conditions
  • Check phase: Perform the setImmediate() callback
  • Close Callbacks stage: Performs the close event callback of the socket

External input data –> Polling stage –> Check stage –> Close callback stage –> Timer detection stage –>I/O callback stage –> IDLE stage Prepare)–> Polling phase (repeated in this order)

reference

  • SetTimeout and setImmediate Mediate Mediate Do not mediate. This article will help you understand the Event Loop
  • Explore javaScript asynchrony and browser update rendering timing from the Event Loop specification
  • Geek Time – How browsers work and practice
  • What is the difference between browser and Node Event loops?