Home Web Front-end JS Tutorial JS operating mechanism: analysis of synchronization, asynchronous and event loop (Event Loop)

JS operating mechanism: analysis of synchronization, asynchronous and event loop (Event Loop)

Aug 07, 2018 pm 03:41 PM

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);
})()
Copy after login

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 of this Website
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

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

TypeScript for Beginners, Part 2: Basic Data Types TypeScript for Beginners, Part 2: Basic Data Types Mar 19, 2025 am 09:10 AM

Once you have mastered the entry-level TypeScript tutorial, you should be able to write your own code in an IDE that supports TypeScript and compile it into JavaScript. This tutorial will dive into various data types in TypeScript. JavaScript has seven data types: Null, Undefined, Boolean, Number, String, Symbol (introduced by ES6) and Object. TypeScript defines more types on this basis, and this tutorial will cover all of them in detail. Null data type Like JavaScript, null in TypeScript

Can PowerPoint run JavaScript? Can PowerPoint run JavaScript? Apr 01, 2025 pm 05:17 PM

JavaScript can be run in PowerPoint, and can be implemented by calling external JavaScript files or embedding HTML files through VBA. 1. To use VBA to call JavaScript files, you need to enable macros and have VBA programming knowledge. 2. Embed HTML files containing JavaScript, which are simple and easy to use but are subject to security restrictions. Advantages include extended functions and flexibility, while disadvantages involve security, compatibility and complexity. In practice, attention should be paid to security, compatibility, performance and user experience.

See all articles