Short story – Easy to understand, efficient interview

A story:

In a restaurant, all the customers are in an orderly line to order, but some customers have to wait for someone, so they don’t order. The chef started the first round of customers’ dishes. The dishes are ready, the first round of guests is finished, and the waiter clears the table for the waiting guests. The guests keep coming…

Restaurant flow chart:

First wave of people who have ordered -> Finished, clear the table -> First wave of people who haven't ordered -> Finished, clear the table -> second wave of people who have ordered ->...Copy the code

Browser flowchart:

Execute synchronization task -> Render GUI -> Execute previous asynchronous task -> Render GUI -> Execute new synchronization task ->...Copy the code

The second story

Then story 1: Later, a VIP customer appeared, named Promise. According to the restaurant’s ES6 regulations, VIP queue-jumping is called “micro-task”.

Flow chart of ES6 restaurant:

First wave of people who have ordered -> VIP jump the queue -> Finish eating, clear the table -> first wave of people who have not ordered -> VIP jump the queue -> Finish eating, clear the table -> second wave of people who have ordered ->...Copy the code

Browser execution flowchart:

Perform synchronization task -> Promise callback -> Render GUI -> Perform previous asynchronous task -> Promise callback -> render GUI -> Perform a new synchronization task ->...Copy the code

conclusion

  1. When a synchronous task is executed, an asynchronous task is found and the callback of the asynchronous task is added to the task queue of the next round.
  2. The promise, promise and mutationOberver introduced by the new ES6 standard are collectively known as microtasks.
  3. After performing the synchronous task, you perform the microtask, then render the GUI, and finally handle the regular asynchronous task
  4. Regular synchronous and asynchronous tasks are collectively called macro tasks, while Promise and mutationOberver are collectively called microtasks.

Micro and macro task flow chart:

Macro Tasks -> Micro Tasks -> Render GUI -> Macro Tasks -> Render GUI -> Macro Tasks -> Render GUI -> Macro Tasks ->...Copy the code