[js log] Macro task, micro task and event loop

1. Macro tasks and micro tasks

Speaking of macro tasks and micro tasks, we have to mention Event Loop

The essence of JS is a single line:

  1. Generally speaking, non-blocking tasks are synchronized and completed directly on the execution stack of the main thread.

  2. Generally speaking, blocking tasks will be executed asynchronously, and asynchronous work will generally be handed over to other threads for completion, and then the callback function will be placed in the event queue.
    Insert picture description here
    When the task of the main thread is executed (the execution stack is empty), JS will ask the event queue

Execute a macro task (execute the synchronization code first) -> execute all micro tasks -> UI render -> execute the next macro task -> execute all micro tasks -> UI render ->...

According to the HTML Standard, after one round of event loop execution ends, UI render will start before the next round of event loop execution. That is: after the macro-task task is executed, and then all the micro-task tasks are executed, the current round of the loop ends and the UI render is executed. After the UI render is completed, the next round of loop follows. But UI render may not be executed, because the performance consumed by UI rendering needs to be considered whether there has been any UI changes
Insert picture description here

2. What are macro tasks and micro tasks?

2.1 Macro task

Insert picture description here
UI Rendering is listed in some places, saying that this is also a macro task, but after reading the HTML specification document, I found that this is obviously an operation step parallel to the micro task
requestAnimationFrame can also be regarded as a macro task for the time being. The definition of requestAnimationFrame in MDN is, The operation performed before the next page redraw, and the redraw also exists as a step of the macro task, and this step is later than the execution of the micro task

2.2 Micro tasks

Insert picture description here

2.3 Event-Loop

But back to reality, JavaScript is a single-process language that cannot handle multiple tasks at the same time, so when to perform macro tasks and when to perform micro tasks? We need to have such a judgment logic.
After completing a business, the teller will ask the current customer if there are other businesses that need to be handled. (Check if there are any micro-tasks to be processed) After the
customer clearly informs that there is nothing to do, the teller checks to see if there are anyone waiting to handle the business. (End this macro task, check whether there is any macro task to be processed)
This inspection process is continuous, and it will be performed every time a task is completed, and this operation is called an event loop. (This is a very simple description, in fact it will be a lot more complicated)
And as mentioned above, a teller can only handle one thing at a time, even if these things are proposed by a customer, so it can be considered that microtasks are also There is a queue, which is roughly a logic like this:

const macroTaskList = [
  ['task1'],
  ['task2', 'task3'],
  ['task4'],
]

for (let macroIndex = 0; macroIndex < macroTaskList.length; macroIndex++) {
    
    
  const microTaskList = macroTaskList[macroIndex]
  
  for (let microIndex = 0; microIndex < microTaskList.length; microIndex++) {
    
    
    const microTask = microTaskList[microIndex]

    // 添加一个微任务
    if (microIndex === 1) microTaskList.push('special micro task')
    
    // 执行任务
    console.log(microTask)
  }

  // 添加一个宏任务
  if (macroIndex === 2) macroTaskList.push(['special macro task'])
}

// > task1
// > task2
// > task3
// > special micro task
// > task4
// > special macro task

The reason for using two for loops is that it is convenient to perform push operations (adding some tasks) inside the loop, so that the number of iterations is dynamically increased.

And to be clear, the Event Loop is only responsible for telling you which tasks should be executed, or which callbacks are triggered, and the real logic is still executed in the process.

Understand the external links of these three

3. Priority of the task

  • Macrotask:
    main code block> setImmediate> MessageChannel> setTimeout / setInterval (Most browsers will prioritize DOM event callbacks because they want to improve user experience and give user feedback, followed by callbacks for network IO operations, then UIrender, and then The order of is elusive. In fact, the performance of different browsers is not the same, so I won’t discuss too much here.)

  • Microtask: process.nextTick> Promise = MutationObserver

  • The execution sequence of the Event Loop is as follows:
    first execute the synchronous code, which is a macro task.
    After all the synchronous code is executed, the execution stack is empty, and query whether there is asynchronous code to be executed
    . All the micro tasks are
    executed. When all the micro tasks are executed, such as It is necessary to render the page
    and then start the next round of Event Loop to execute the asynchronous code in the macro task, which is the callback function in setTimeout

That is to say, the order of task execution is established and prioritized:

If there is already a setTImeout macro task in the queue, and the macro task of the main code is added later, the task of the main code will be inserted in the queue.

4. Supplement the async/await function

Because, async/await is essentially some encapsulation based on Promise, and Promise is a kind of microtask. So the effect of using the await keyword is similar to that of Promise.then:

setTimeout(_ => console.log(4))

async function main() {
    
    
  console.log(1)
  await Promise.resolve()
  console.log(3)
}

main()

console.log(2)

The code of the async function before await is executed synchronously, which can be understood as the code before await belongs to the code passed in when the new Promise is passed, and all the code after await is the callback in the Promise.then

Guess you like

Origin blog.csdn.net/u013034585/article/details/106130027