Message queues and event loops
1. The first version of the threading model
For some identified tasks, you can use oneSingle thread to process sequentiallyThese tasks.
2. Version 2 of the Threading model
To receive and process new tasks during thread execution, loop statements and event systems (i.e., event loops) need to be introduced.
Improvements over the first edition:
- The first introduces looping by adding a for loop to the end of a thread statement, which will continue to execute.
- The second point introduces events that wait for input tasks while a thread is running, activate the thread once it receives user input, and then execute the task.
3. The third version of the Threading model
If you want to receive tasks from other thread tasks, you need to import message queues.
Improvements over the second version of the threading model, where all tasks come from within the thread:
- First, add a message queue.
- Second: new tasks generated in the IO thread are added to the end of the system message queue;
- Third: The render main thread executes the task by reading it in a loop from the head of the message queue.
A message queue is a data structure that holds tasks to be executed. It conforms to the “first in, first out” feature. To add tasks, add them to the end of the queue; To fetch a task, fetch it from the head of the queue.
4. Send tasks across processes
If another process wants to send a task to the main thread of the page, it sends the task via IPC to the renderer’s IO thread, which then sends the task to the main thread of the page.
As can be seen from the figure,The renderer has an IO thread that receives messages from other processesOnce received, the messages are assembled into tasks and sent to the render main thread.
- Message queuing mechanism is not very flexible, so microtasks are introduced to adapt to efficiency and real time.
Disadvantages of using single threads
- The first problem is how to handle high-priority tasks.
- Add microtasks to balance efficiency and real-time.
- The second problem is how to solve the problem that a single task takes too long to execute.
- Add a callback function
WebAPI: setTimeout summary
Browser pages are driven by message queues and event loops.
To support the implementation of timers, browsers add delay queues.
Some considerations for using setTimeout:
- If the current task is executed for a long time, the timer task execution will be affected.
- If setTimeout has nested calls, the minimum interval is set to 4 milliseconds
- For inactive pages, setTimeout is executed with a minimum interval of 1000 milliseconds
- The delay time reaches the maximum value of 2147483647 ms. If the delay exceeds the maximum value, the timer is executed immediately.
- The “this” in the setTimeout callback is not intuitive. It will be the “this” object for the callback, which can be resolved using the arrow function or bind.
Note: Delay queues are also macro tasks. In fact, Blink maintains a number of queues with different priorities, which are filled with macro tasks.
The delay message queue mainly puts some scheduled tasks, such as JavaScript set timer callback, and some internal browser scheduled callback tasks! This type of task will not be executed until after the specified interval!
In a normal message queue, tasks are executed sequentially, with no relational time interval required.
A microtask is executed at some point during the execution of a macro task, usually near the end of the macro task.
Macro task
Most of the tasks in the page are executed on the main thread. These tasks include:
- Render events (such as PARSING DOM, calculating layout, drawing);
- User interaction events (such as mouse click, page scrolling, zooming in and out, etc.);
- JavaScript script execution events;
- Network request completed, file read/write completed event.
Disadvantages:
Macro task time granularity is relatively large, execution time interval can not be precisely controlled, can not meet some high real-time requirements. Such as the need to listen for DOM changes.
Micro tasks
The concept of asynchronous callback comes in two main ways:
- The first is that the asynchronous callback function is encapsulated as a macro task, added to the end of the message queue, and executed when the loop executes the task. (For example, setTimeout and XMLHttpRequest callbacks are implemented this way.)
- The second method is executed after the execution of the main function but before the completion of the current macro task, usually in the form of microtasks.
What exactly is a microtask?
- A microtask is a function that needs to be executed asynchronously, after the completion of the main function but before the completion of the current macro task.
How do microtasks come about?
-
The first way is to use MutationObserver to monitor a DOM node, and then modify the node through JavaScript, or add or remove partial nodes to the node. When the DOM node changes, the micro-task of recording the DOM changes is generated.
-
The second approach: use promises, which also produce microtasks when promise.resolve () or promise.reject () is called.
How is the microtask queue executed?
- When the JavaScript in the current macro task is about to complete, that is, when the JavaScript engine is ready to exit the global execution context and empty the call stack, the JavaScript engine checks the microtask queue in the global execution context and executes the microtasks in the queue in order
- The WHATWG refers to the point at which a microtask is performed as a checkpoint
Promise
Promise addresses the issue of asynchronous coding styles.
Problems with asynchronous programming: Too many asynchronous callbacks cause code logic to be discontinuous,
How to solve it?
Encapsulate asynchronous code, streamline the process, and focus on input data and output.
New problem: callback hell
The reason:
- The first is nested calls, and because you have too many nested callback functions you can easily get yourself into callback hell and make your code very unreadable.
- The second is the uncertainty of the task. There are two possibilities (success or failure) for the processing result of each task, so these two possibilities need to be dealt with respectively after the execution of each task.
Solution:
Promise: Eliminate nested calls and multiple error handling
How does Promise handle nested callbacks?
- Promise implements delayed binding of callback functions.
- Passes the return value of the callback function onResolve to the outermost layer.
How does Promise handle exceptions? Use the last object to catch all exceptions:
- Errors on the Promise object are “bubbling” and are passed backwards until they are processed by the onReject function or caught by a catch statement.
- With this bubbling feature, there is no need to catch exceptions individually in each Promise object.
async/await
ES7 introduces async/await, which is a major improvement over asynchronous JavaScript programming, providing the ability to access resources asynchronously using synchronous code without blocking the main thread, and making code logic clearer.
A generator function is an asterisk function that can be paused and resumed.
Why can functions pause and resume?
- Coroutines are a much lighter form of existence than threads
- A thread can also have more than one coroutine, which is not managed by the operating system kernel but completely controlled by the program (that is, executed in user mode). The benefit of this is that the performance is greatly improved and the resources are not consumed like thread switching.
Write in the last
Learning resources from Geek Time – Teacher Li Bing “Browser working principle and Practice”. Next, let’s check in every day
- Day 01 Chrome architecture: Why 4 processes with only 1 page open?
- Day 02 TCP: How to ensure that a page file can be delivered to the browser in its entirety?
- Day 03 HTTP Request Flow: Why do many sites open quickly the second time?
- Day 04 Navigation flow: What happens between entering the URL and presenting the page?
- Day 05 Rendering Flow: How do HTML, CSS, and JavaScript become pages?
- JavaScript execution mechanisms in the Day 06 browser
- Day 07 V8 how it works
- Page loop system in Day08 browser