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

In-depth understanding of JavaScript execution mechanism

不言
Release: 2018-08-31 10:12:23
Original
974 people have browsed it

The content this article brings to you is about in-depth understanding of JavaScript execution mechanism. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

First of all, what we all know is that JavaScript is a single-threaded language, so we can conclude:

JavaScript is executed in the order of statements

First look:

let a = '1'
console.log(a)

let b = '2'
console.log(b)
Copy after login

Obviously everyone knows the result, output 1, 2 in sequence

However, another way:

setTimeout(function() {
    console.log(1)
})

new Promise(function(resolve) {
    console.log(2)
    for(var i = 0;i< 10;i++){
        i === 10 && resolve()
    }
}).then(function() {
    console.log(3)
})
console.log(4)
Copy after login

At this time, look at the sequential execution of the code, output 1, 2, 3, 4. Okay, put it in the browser and run it, what? The output is actually 2, 4, 3, 1. What about executing them in order as promised? Next, we need to understand the execution mechanism of JavaScript.

Single-threaded

First of all, JavaScript is a single-threaded language. In the latest Web-worker launched in HTML5, the core of JavaScript being a single-threaded language has not changed. Therefore, JavaScript multi-threading is simulated based on single thread. So keep in mind that JavaScript is a single-threaded language.

Event loop

Tasks are divided into two categories:

  • Synchronous tasks

  • Asynchronous tasks

When we open the page, the rendering of the page is a lot of synchronous tasks, and the time-consuming tasks of loading images and audio resources are asynchronous tasks. The main content of the time loop is:

  1. When a task enters the execution stack, it is judged whether it is a synchronous task or an asynchronous task. If it is a synchronous task, it enters the main thread for execution and asynchronously enters the Event Table. Register function.

  2. When the specified event is completed, the Event Table will move this function into the event queue

  3. After the task in the main thread is completed, go The task queue reads the corresponding function and enters the main thread to execute

  4. The above process is repeated continuously, which constitutes an event loop

where js The engine has a monitoring process that constantly checks whether the main thread execution stack is empty. Once it is empty, it will go to the time queue to check whether there are functions waiting to be called.

For example:

setTimeout( function() {
    console.log(1)
}, 0)
console.log(2)
Copy after login
  • First setTimeout enters the Event Table

  • Execute console.log(2)

  • The function executed by setTimeout enters the event queue

  • The main thread reads the function execution from the event queue

This is The reason why the function will not be executed immediately even if setTimeout(fn, 0) is set. However, even if the main thread is empty, 0ms cannot be reached. According to the HTML standard, the minimum is 4ms.

setInterval

There is also a function similar to setTimeout. For setInterval, it is executed in a loop. Regarding the execution sequence, setInterval will place the registered function into the Event Queue at specified intervals. If the previous task takes too long, you also need to wait.

But one thing to note is that for setInterval(fn, ms), it is not executed once every ms, but every ms There will be fn entering the task queue. That is to say, if the execution event of the callback function of setInterval exceeds the delay ms, then the event interval will not be visible.

Promise and process.nextTick(callback)

In addition to generalized synchronous tasks and asynchronous tasks, there are also more detailed divisions of tasks, divided into:

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

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

The order of the event loop determines the execution order of the js code. After entering the overall code (macro task), the first cycle starts. Then execute all microtasks. Then start from the macro task again, find one of the task queues to be executed, and then execute all micro tasks.

Use a piece of code to illustrate:

setTimeout(function() {
    console.log('1');
})

new Promise(function(resolve) {
    console.log('2');
    resolve()
}).then(function() {
    console.log('3');
})

console.log('4');
Copy after login
  • This code is used as a macro task to start the first cycle

  • First When setTimeout is encountered, its callback function enters the macro task event queue

  • When Promise,Promise## is encountered #Execute immediately, output 2, thenThe task enters the microtask event queue

  • When the console is encountered below, output 4

  • The first macro task ends, look at the micro task event queue, execute

    then, output 3

  • The first round of loop ends, look at the macro task queue There is a setTimeout callback function executed, and the output is 1

  • . All results are: 2, 4, 3, 1

Okay, now we understand the basics After the principle, let’s look at a more complicated one:

console.log('1');

setTimeout(function() {
    console.log('2');
    process.nextTick(function() {
        console.log('3');
    })
    new Promise(function(resolve) {
        console.log('4');
        resolve();
    }).then(function() {
        console.log('5')
    })
})
process.nextTick(function() {
    console.log('6');
})
new Promise(function(resolve) {
    console.log('7');
    resolve();
}).then(function() {
    console.log('8')
})

setTimeout(function() {
    console.log('9');
    process.nextTick(function() {
        console.log('10');
    })
    new Promise(function(resolve) {
        console.log('11');
        resolve();
    }).then(function() {
        console.log('12')
    })
})
Copy after login
I don’t know what your answer is? Next, let’s analyze it:

First round:

  1. First the entire code enters the main thread as a macro task, and first encounters

    console. log()Output 1

  2. Encounters the first

    setTimeout() Enters the macro task queue

  3. Encountered

    Process.nextTick()Enter microtask queue

  4. Then encounter Promise, execute immediately, output 7, then is added to the microtask queue

  5. Encounter the second setTimeout, enter the macro task queue

  6. Then execute two micro tasks

  7. ExecutionProcess.nextTick()Output 6

  8. Execute then, output 8

This is the first The cycle is completely over, and the second round of event loop is carried out, that is, the first setTimeout

  1. first encounters console.log(), output 2

  2. encountered Process.nextTick(), enter the microtask queue

  3. encounteredPromiseImmediately execute output 4, thenEnter the microtask queue

  4. Then execute the first microtask, output 3

  5. Execute then and output 5

so that the second round of event loop ends, and finally execute the second setTimeout, the second setTimeoutThe principle is similar to the above, so I won’t repeat the explanation. So the final result is: 1,7,6,8,2,4,3,5,9,11,10,12

Related recommendations:

Detailed explanation of js execution mechanism examples

Event Loop of JavaScript running mechanism

The above is the detailed content of In-depth understanding of JavaScript 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