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

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

不言
不言Original
2018-08-07 15:41:281485browse

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