Table of Contents
Single-threaded
Event loop
setInterval
Promise and process.nextTick(callback)
Home Web Front-end JS Tutorial In-depth understanding of JavaScript execution mechanism

In-depth understanding of JavaScript execution mechanism

Aug 31, 2018 am 10:12 AM
javascript

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!

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

Video Face Swap

Video Face Swap

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

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)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles