search
HomeWeb Front-endJS TutorialJS operating mechanism: analysis of synchronization, asynchronous and event loop (Event Loop)

The content of this article is about the JS operating mechanism: analysis of synchronization, asynchronous and event loop (Event Loop). It has certain reference value. Friends in need can refer to it. I hope it will help You helped.

1. Why is JS single-threaded

## A major feature of the Javascript language is that it is single-threaded and can only do the same thing at the same time. So why can't JS be multi-threaded?

As a browser scripting language, the main purpose of Javascript is to interact with users and operate the DOM, which determines that it can only be single-threaded, otherwise it will cause very complex synchronization problems. . For example: Suppose Javascript has two threads at the same time. One thread adds content to a certain DOM node, and the other thread deletes a node. In this case, which one should the browser use?

Therefore, in order to avoid complexity, Javascript has been single-threaded since its birth. This has become the core feature of this language and will not change in the future.

In order to take advantage of the computing power of multi-core CPUs, HTML5 proposes the Web Woker standard, which allows Javascript scripts to create multiple threads, but the child threads are completely controlled by the main thread and cannot operate the DOM. Therefore, this new standard does not change the single-threaded nature of JavaScript.

2. Synchronization and asynchronousness## Assume there is a function A:

A(args...){...}

Synchronization: If the caller can immediately get the expected result when calling function A, then this function is synchronous.

Asynchronous: If when calling function A, the caller cannot get the expected result immediately, but needs to obtain it in the future through certain means (time-consuming, delay, event triggering), then this function is Asynchronous.

3.

How JS implements asynchronous operationsAlthough JS is single-threaded, the browser’s kernel is multi-threaded. Browsing The browser opens up additional threads for some time-consuming tasks. Different asynchronous operations will be scheduled and executed by different browser kernel modules. For example, onlcik, setTimeout, and ajax are processed in different ways, respectively, by the DOM in the browser kernel. Bingding, network, and timer modules are executed. When the executed task gets the running result, the corresponding callback function will be placed in the task queue. Therefore, JS has always been single-threaded, and it is the browser that implements asynchronous operations.

In the picture above, when DOM requests, ajax requests, setTimeout and other WebAPIs are encountered in the call stack, they will be handed over to other modules of the browser kernel for processing, webkit In addition to the Javascript execution engine, the kernel has an important module called the webcoew module. For the three APIs mentioned by WebAPIs in the figure, webcore provides DOM Binding, network, and timer modules respectively to handle the underlying implementation. When these modules finish processing these operations, put the callback function into the task queue, and then wait for the tasks in the stack to be executed before executing the callback function in the task queue.

Summary:

#1. All codes must be executed through calls in the function call stack

2. When encountering the APIs mentioned in the previous article, it will be handed over to other modules of the browser kernel for processing

3. The callback function is stored in the task queue

4 , wait until the task in the call stack is executed, and then go back to execute the task in the task queue

The operating mechanism of JS is as follows:

(1) All synchronization tasks are Executed on the main thread to form an execution stack.

(2) In addition to the main thread, there is also a "task queue". As long as the asynchronous task has the operation result, an event (callback function) is placed in the "task queue".

(3) Once all synchronization tasks in the "execution stack" are completed, the system will read the "task queue" to see what events are in it. Those corresponding asynchronous tasks end the waiting state. Enter the execution stack and start execution.

(4) The main thread keeps repeating the third step above

Task QueueIt has been mentioned above Go to the task queue, so what exactly is the task queue? For example

In the ES6 standard, the task queue is divided into macro tasks (macro-task) and micro tasks (micro-task)

1.macro-task includes: script (whole code), setTimeout, setInterval, setImmediate, I/O, UI rendering

2.micro-task includes: process.nextTick, Promises, Object.observe, MutationObserver

The order of the event loop is to start the first loop from script, then the global context enters the function call stack. When encountering a macro-task, it is handed over to the module that handles it. After processing, the callback function is put into the macro. In the -task queue, when encountering a micro-task, its callback function is also put into the micro-task queue. Until the function call stack is cleared and only the global execution context is left, all micro-tasks start to be executed. After all executable micro-tasks have been executed. The loop executes a task queue in the macro-task again, and then executes all micro-tasks after execution, and the loop continues.

Next, let’s analyze the execution process:

(function test() {
    setTimeout(function() {console.log(4)}, 0);
    new Promise(function executor(resolve) {
        console.log(1);
        for( var i=0 ; i<10000 ; i++ ) {
            i == 9999 && resolve();
        }
        console.log(2);
    }).then(function() {
        console.log(5);
    });
    console.log(3);
})()

1. Push the global context onto the stack and start executing the code in it.

2. Execute to setTimeout, hand it to the timer module as a macro-task, and then put its callback function into its own queue.

3. Execute to the Promise instance and push the Promise onto the stack. The first parameter is to directly execute the output 1 in the current task.

4. Execute the loop body, encounter the resolve function, push it into the stack and pop it after execution, change the promise status to Fulfilled, and then output 2

5. When encountering the then method, it will be used as a micro-task , enter the Promise task queue.

6. Continue to execute the code and output 3.

7. After outputting 3, the first macrotask code is executed and all microtasks in the queue are executed. Then's callback function is pushed onto the stack and then popped out, outputting 5.

8. At this time, all micao-task execution is completed, and the first cycle ends. The second round of loop starts from the task queue of setTimeout. The callback function of setTimeout is pushed into the stack and then popped out. At this time, 4 is output.

Summary:

1. Different tasks will be put into different task queues.

2. Execute macro-task first, wait until the function call stack is cleared, and then execute all micro-tasks in the queue.

3. Wait until all micro-tasks are executed, and then start execution from a task queue in the macro-task, and the loop continues like this.

4. When there are multiple macro-task (micro-task) queues, the order of the event loop is executed in the order written in the macro-task (micro-task) classification above.

Summary:

#When the JS engine parses the JS code, it will create a main thread and a call Stack (call-stack), when a task in a call stack is processed, others have to wait.

When some asynchronous operations are executed, they will be handed over to other modules of the browser kernel for processing (taking webkit as an example, it is the webcore module). After the processing is completed, the task (callback function) Put in the task queue.

Generally, the callback functions of different asynchronous tasks will be put into different task queues. After all the tasks in the call stack are executed, the tasks in the task queue (callback functions) will be executed. )

Recommended related articles:

Usage of this keyword in javascript (with code)

What are the js data types? Summary of data types of js

The above is the detailed content of JS operating mechanism: analysis of synchronization, asynchronous and event loop (Event Loop). For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools