Home > Web Front-end > JS Tutorial > body text

A brief analysis of JS execution mechanism

零到壹度
Release: 2018-03-28 14:55:27
Original
1376 people have browsed it

This article mainly shares with you a method of briefly analyzing the JS execution mechanism. It has a good reference value and I hope it will be helpful to everyone. Let’s follow the editor and take a look.

First of all, please keep 2 points in mind:

(1 ) JS is a single-threaded language

#(2) The Event Loop of JS is the execution mechanism of JS. A deep understanding of the execution of JS is equivalent to a deep understanding of the event loop in JS

1. Three soul questions: Why is JS single-threaded? Why does it need to be asynchronous? How is single-threading implemented? What about asynchronous ones? The emergence of

technologies is closely related to application scenarios in the real world.

Similarly, we will answer these three questions based on real-life scenarios

(1) Why is JS single-threaded?

JS was originally designed to be used in browsers, so imagine if JS in the browser was multi-threaded.

Thinking about it this way, it should be easy to understand why JS is designed to be single-threaded.

(2) Why does JS need asynchronous?


1

2

3

4

5


##Scene description

:

So now there are

2 processes,process1 process2 ,Because it is a multi-processJS,so they operate on the same dom,at the same time

process1 Deleted the dom, and process2 Edited the dom,issued 2 contradictory commands at the same time,How should the browser execute it?


##1

2

3

4


Scene description

:

If asynchronous

does not exist in JS, can only Top-down execution,If the parsing time of the previous line is very long,then the following code will be blocked.

For users,blocking means"stuck",This leads to a poor user experience

So, there is asynchronous execution in JS.

(3) How does single-thread JS achieve asynchronous implementation?

Since JS is single-threaded, it can only be executed in one thread How to implement asynchronous execution?

is through the event loop (event loop). If you understand the event loop mechanism, you will understand the execution mechanism of JS

2. event loop(1) in JS

Example 1, observe its execution sequence

 console.log(1)
    
    setTimeout(function(){
        console.log(2)
    },0)
 
    console.log(3)
Copy after login

The running result is: 1 3 2

In other words, the function in setTimeout is not executed immediately, but is delayed for a period of time and is executed only after certain conditions are met. This type of code is called asynchronous code.

So, here we first know a classification method in JS, which is to divide tasks into: synchronous tasks and asynchronous tasks

Picture description

According to this classification Method: The execution mechanism of JS is

  • First determine whether JS is synchronous or asynchronous. If it is synchronous, it will enter the main process, if it is asynchronous, it will enter the event table

  • The asynchronous task registers the function in the event table. When the trigger condition is met, it is pushed into the event queue

  • The synchronous task enters the main thread and is executed until the main thread is idle. Check the event queue to see if there are executable asynchronous tasks. If there are, push them into the main process

The above three steps are executed in a loop. This is the event loop

So for the above example, can you describe its execution sequence?

in setTimeout


##1

2

3

4

5


console.log(1) is a synchronization task,put it in the main thread

setTimeout() is an asynchronous task , is put into event table, 0 will be pushed into event queue

seconds later

console.log(3 is a synchronization task ,Put it in the main thread

When 1 3 is in After the control bar is printed, , the main thread goes to event queue(Event Queue) to see if there is any The executed function,executes the function

3.JS中的event loop(2)

所以,上面关于event loop就是我对JS执行机制的理解,直到我遇到了下面这段代码

例2:

setTimeout(function(){
     console.log('定时器开始啦')
 });
 
 new Promise(function(resolve){
     console.log('马上执行for循环啦');
     for(var i = 0; i
Copy after login

尝试按照,上文我们刚学到的JS执行机制去分析


1

2

3

4

5

6

7


##setTimeout is an asynchronous task , is placed in event table

new Promise is a synchronous task, are placed in the main process , Directly execute printing console.log('Execute the for loop now')

.then# The function in ## is asynchronous task, is placed in event table

console.log('Code execution ends') is the synchronization code , is placed in the main process , is executed directly

So, the result is [execute the for loop immediately - the code execution ends - the timer starts - the then function is executed]?

After executing it personally, the result is not like this, but [execute immediately The for loop - the code execution ends - the then function is executed - the timer starts]

So, is it the execution order of asynchronous tasks, not the order before and after, but other regulations? In fact, according to asynchronous and The synchronization division method is not accurate.

The accurate division method is:

  • macro-task (macro task): including the overall code script, setTimeout, setInterval

  • micro-task (micro-task): Promise, process.nextTick

A brief analysis of JS execution mechanism

##According to this classification method: the execution mechanism of JS is

  • Execute a macro task. If a micro task is encountered during the process, put it in the [event queue] of the micro task.

  • Current macro After the task execution is completed, the [Event Queue] of the microtask will be viewed, and all microtasks in it will be executed in sequence

Repeat the above 2 steps, combined with event loop (1) event loop (2) , which is a more accurate JS execution mechanism.

Try to analyze Example 2 according to the execution mechanism you just learned:


1

2

3

4

5

6

7

8

9

10

11

12

13

14


First execute the macro task under script,encounters setTimeout,put it in the [queue] of the macro task

Encounter new PromiseDirectly execute ,print "Execute the for loop immediately"

Encounterthenmethod,is a microtask,Put it into the microtask [queue]

Print "Code execution ends"

This round of macro tasks has been executed,Check the current round of micro tasks,It was found that there is a function in the then method, Print"The then function is executed"

This is it,This round's event loop All completed.

下一轮的循环里,先执行一个宏任务,发现宏任务的【队列】里有一个 setTimeout里的函数,执行打印"定时器开始啦"

所以最后的执行顺序是【马上执行for循环啦 — 代码执行结束 — 执行then函数啦 — 定时器开始啦】

4. 谈谈setTimeout

这段setTimeout代码什么意思? 我们一般说: 3秒后,会执行setTimeout里的那个函数

setTimeout(function(){
    console.log('执行了')
 },3000)
Copy after login

但是这种说并不严谨,准确的解释是: 3秒后,setTimeout里的函数被会推入event queue,而event queue(事件队列)里的任务,只有在主线程空闲时才会执行。

所以只有满足 (1)3秒后 (2)主线程空闲,同时满足时,才会3秒后执行该函数

如果主线程执行内容很多,执行时间超过3秒,比如执行了10秒,那么这个函数只能10秒后执行了

The above is the detailed content of A brief analysis of JS execution mechanism. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template