Analysis of the event loop mechanism of js

Analysis of the event loop mechanism of js

Preface

As we all know, JavaScript is single-threaded at its core, but browsers can handle asynchronous requests very well. So why is that? The principle behind this has a lot to do with the event loop mechanism.

Before exploring the event loop, we need to understand the browser execution thread~~

The browser's rendering process is multi-threaded. Each tab in the browser represents an independent process. The browser kernel is one of the browser's multi-processes and is mainly responsible for page rendering, script execution, event processing, etc. The threads it contains are the following

GUI rendering thread: responsible for rendering pages, parsing HTML, and CSS to form a DOM tree;
JS engine thread: interprets and executes code, user input, and network requests;
Event processing thread: After click, mouse and other interactive events occur, the event function is put into the queue;
Timer triggers thread: After the time is up, the execution function is pushed into the task queue;
http network request thread: processes user's get and post requests, and pushes the returned results into the task queue.

After understanding the browser rendering process, you also need to understand the operating mechanism of JS. The operating mechanism of JS is the event loop

Execution Stack

The environment in which JS runs is called the host environment.

Execution stack: call stack, a data structure used to store the execution environment of various functions. Before each function is executed, its related information will be added to the execution stack. Before a function is called, an execution environment is created and then added to the execution stack; after a function is called, the execution environment is destroyed.

Event Loop

All tasks in js can be divided into synchronous tasks and asynchronous tasks. Synchronous tasks are tasks that are executed immediately. Synchronous tasks generally enter the main thread directly for execution; while asynchronous tasks are tasks that are executed asynchronously, such as ajax network requests, setTimeout timing functions, etc., which are all asynchronous tasks. Asynchronous tasks are coordinated through the task queue (first-in-first-out) mechanism. Synchronous and asynchronous tasks enter different execution environments respectively. Synchronous tasks enter the main thread, that is, the main execution stack, and asynchronous tasks enter the task queue. When the tasks in the main thread are completed and are empty, the task queue will be read to read the corresponding tasks and pushed into the main thread for execution. This constant repetition is what we call the Event Loop. The specific process is shown in the figure below.

In the event loop, each loop operation is called a tick. The steps of each tick task key can be summarized as follows: 1. Execute a macro task (if there is no macro task in the stack, get it from the event queue); 2. If a micro task is encountered during the execution, add it to the task queue of the micro task; 3. After the macro task is executed, all micro tasks in the current micro task queue are executed immediately (in sequence); 4. After the current macro task is executed, start checking the rendering, and then the GUI thread takes over the rendering; 5. After the rendering is completed, the JS thread continues to take over and start the next macro task (get it from the event queue)

Macro tasks mainly include: script (whole code), setTimeout, setInterval, I/O, UI interaction events, setImmediate (Node.js environment)
Microtasks mainly include: Promise, MutaionObserver, process.nextTick (Node.js environment)

Event loop example

console.log('script start');
//The whole script enters the main thread as the first macro task, encounters console.log, and outputs script start
setTimeout(function() {
  console.log('setTimeout');
}, 0);
//When encountering setTimeout, its callback function is distributed to the macro task Event Queue Promise.resolve().then(function() {
  console.log('promise1');
}).then(function() {
  console.log('promise2');
});
//When encountering Promise, its then function is assigned to the microtask Event Queue, recorded as then1. Then, another then function is encountered and assigned to the microtask Event Queue, recorded as then2
console.log('script end');
//When encountering console.log, output script end

In this way, there are three tasks in the Event Queue: macro task: setTimeout micro tasks: then1, then2. Execute the microtask first then1, output promise1, then execute then2, output promise2, so that all microtasks are cleared

Execute the setTimeout task and output setTimeout. So far, the output order is: script start, script end, promise1, promise2, setTimeout

Summarize:

JavaScript is a single-threaded language. Asynchronous operations are placed in the event loop queue and wait for the main execution stack to execute. There is no dedicated asynchronous execution thread.

This is the end of this article about the event loop mechanism of js. For more relevant js event loop content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • An article explains the event loop mechanism in JS
  • Let's talk briefly about JavaScript's event loop mechanism
  • Analysis of JavaScript's event loop mechanism
  • Detailed explanation of JS browser event loop mechanism
  • Detailed explanation of JavaScript event loop mechanism
  • Example analysis of js event loop mechanism
  • Detailed example of event loop mechanism in JS

<<:  Analyze the sql statement efficiency optimization issues of Mysql table reading, writing, indexing and other operations

>>:  CentOS8 network card configuration file

Recommend

Implementation of interactive data between QT and javascript

1. Data flows from QT to JS 1. QT calls the JS fu...

Xhtml special characters collection

nbsp &#160; no-break space = non-breaking spa...

MySQL Innodb key features insert buffer

Table of contents What is insert buffer? What are...

How to show or hide common icons on the desktop in Windows Server 2012

Windows Server 2012 and Windows Server 2008 diffe...

Div nested html without iframe

Recently, when doing homework, I needed to nest a ...

How to solve the front-end cross-domain problem using Nginx proxy

Preface Nginx (pronounced "engine X") i...

MySQL database architecture details

Table of contents 1. MySQL Architecture 2. Networ...

JavaScript Basics Variables

Table of contents 1. Variable Overview 1.1 Storag...

JavaScript implements changing the color of a web page through a slider

Hello everyone, today when I was looking at the H...

How to cancel the background color of the a tag when it is clicked in H5

1. Cancel the blue color of the a tag when it is ...

Mysql modify stored procedure related permissions issue

When using MySQL database, you often encounter su...

Implementation of MySQL GRANT user authorization

Authorization is to grant certain permissions to ...

Zabbix monitors Linux hosts based on snmp

Preface: The Linux host is relatively easy to han...