Home Web Front-end JS Tutorial Detailed explanation of JavaScript event loop mechanism - Lecture 1

Detailed explanation of JavaScript event loop mechanism - Lecture 1

Mar 07, 2018 pm 02:56 PM
javascript js mechanism

Event loop mechanism in Javascript, many articles only say that Javascript events are divided into synchronous tasks and asynchronous tasks. When a synchronous task is encountered, it is placed in the execution stack for execution, and when an asynchronous task is encountered, Put it in the task queue and wait until the execution stack is completed before executing the events in the task queue. This article is very good! We together look! Let’s get straight to the point!

Function call stack and task queue

Javascript has a main thread main process and a call-stack (a call stack). While the task in the call stack is being processed, everything else has to wait. When some asynchronous operations such as setTimeout are encountered during execution, they will be handed over to other modules of the browser (taking webkit as an example, the webcore module) for processing. When the delayed execution time specified by setTimeout is reached, task(Callback function) will be put into the task queue. Generally, the callback functions of different asynchronous tasks will be placed in different task queues. After all tasks in the call stack have been executed, then execute the tasks (callback functions) in the task queue.

Using a picture from Philip Roberts's speech "Help, I'm stuck in an event-loop" is

Detailed explanation of JavaScript event loop mechanism - Lecture 1

in the picture above , when the call stack encounters DOM operations, ajax requests, setTimeout and other WebAPIs, it will be handed over to other modules of the browser kernel for processing. In addition to the Javasctipt execution engine, the webkit kernel has an important The module is the webcore 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.

Looking at the event loop mechanism from setTimeout

The following uses an example from Philip Roberts's speech to illustrate how the event loop mechanism executes setTimeout. of.

Detailed explanation of JavaScript event loop mechanism - Lecture 1

First the execution context of the main() function is pushed onto the stack

Detailed explanation of JavaScript event loop mechanism - Lecture 1

The code is then executed and encounters console.log( 'Hi'), at this time log('Hi') is pushed onto the stack. The console.log method is just a common method supported by the webkit kernel, so the log('Hi') method is executed immediately. At this time, 'Hi' is output.

Detailed explanation of JavaScript event loop mechanism - Lecture 1

#When encountering setTimeout, the execution engine adds it to the stack.

Detailed explanation of JavaScript event loop mechanism - Lecture 1

The call stack found that setTimeout is an API in the WebAPIs mentioned before, so after popping it off the stack, the delayed execution function is handed over to the browser's timer module for processing. .

Detailed explanation of JavaScript event loop mechanism - Lecture 1

The timer module handles delayed execution functions. At this time, the execution engine then executes and adds log(‘SJS’) to the stack, and outputs ‘SJS’.

Detailed explanation of JavaScript event loop mechanism - Lecture 1

When the time specified by the delay method in the timer module is up, it is put into the task queue. At this time, all tasks in the call stack have been executed.

Detailed explanation of JavaScript event loop mechanism - Lecture 1

Detailed explanation of JavaScript event loop mechanism - Lecture 1

After the task in the call stack is executed, the execution engine will then check whether there is anything in the execution task queue that needs to be executed. Callback. The cb function here is added to the call stack by the execution engine, and then executes the code inside and outputs 'there'. Wait until the execution is completed before popping it off the stack.

Summary

The above process explains how the browser executes it when it encounters setTimeout. Similar ones are The other APIs mentioned in the previous figure and some other asynchronous operations.
To summarize what was said above, the main points are the following:

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.

Test

for (var i = 0; i < 5; i++) {
    setTimeout(function() {
      console.log(new Date, i);
    }, 1000);
}
console.log(new Date, i);
Copy after login

This code is a JS interview question that 80% of applicants fail from an article I read online not long ago Found in , now we will analyze how this code outputs the final execution state mentioned in the last article:

40% of people will describe it as: 5 -> 5,5,5,5,5, that is, the first 5 is output directly, and after 1 second, 5 5s are output;

1. First, when i=0, the condition is met , the execution stack executes the code in the loop body, and finds that it is setTimeout. After popping it out of the stack, the delayed execution function is handed over to the Timer module for processing.

2. When i=1,2,3,4, the conditions are all met, and the situation is the same as when i=0. Therefore, there are 5 identical delayed execution functions in the timer module.

3. When i=5, the condition is not met, so for loop ends, console.log(new Date, i) is pushed onto the stack, and i at this time has become 5. So the output is 5.

4. At this time, 1s has passed, and the timer module returns the 5 callback functions to the task queue in the order of registration.

5. The execution engine executes the functions in the task queue. Five functions are pushed into the stack for execution and then popped out. At this time, i has become 5. So five 5s are output almost simultaneously.

6. Therefore, the waiting time of 1s is actually only 1s after outputting the first 5. This 1s time is the specified 1s time that the timer module needs to wait before handing the callback function to the task queue. After the execution stack is completed, execute the five callback functions in the task queue. There is no need to wait 1s during this period. Therefore, the output status is: 5 -> 5,5,5,5,5, that is, the first 5 is output directly, and after 1s, 5 5s are output;

Question

After seeing this, I have a general understanding of the event loop mechanism, but if I think about it carefully, there are some other issues worth exploring.
The following is explained through a chestnut:

(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

In this code, there is an extra promise, then we can think about the following question:

1. The task of the promise will be placed In different task queues, what is the execution order of setTimeout's task queue and promise's task queue?

2. Now that you have seen that I have talked about so many tasks, what exactly do the tasks mentioned above include? How is it divided specifically?

If you still don’t understand it well here, then I will go on to explain in detail the event loop mechanism of different tasks.

Related recommendations:

##js event loop mechanism example analysis

The above is the detailed content of Detailed explanation of JavaScript event loop mechanism - Lecture 1. 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)

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

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

The relationship between js and vue The relationship between js and vue Mar 11, 2024 pm 05:21 PM

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

Introduction to the method of obtaining HTTP status code in JavaScript: In front-end development, we often need to deal with the interaction with the back-end interface, and HTTP status code is a very important part of it. Understanding and obtaining HTTP status codes helps us better handle the data returned by the interface. This article will introduce how to use JavaScript to obtain HTTP status codes and provide specific code examples. 1. What is HTTP status code? HTTP status code means that when the browser initiates a request to the server, the service

js method to refresh current page js method to refresh current page Jan 24, 2024 pm 03:58 PM

js methods to refresh the current page: 1. location.reload(); 2. location.href; 3. location.assign(); 4. window.location. Detailed introduction: 1. location.reload(), use the location.reload() method to reload the current page; 2. location.href, you can refresh the current page by setting the location.href attribute, etc.

Deep understanding of the mechanics of CSS layout recalculation and rendering Deep understanding of the mechanics of CSS layout recalculation and rendering Jan 26, 2024 am 09:11 AM

CSS reflow and repaint are very important concepts in web page performance optimization. When developing web pages, understanding how these two concepts work can help us improve the response speed and user experience of the web page. This article will delve into the mechanics of CSS reflow and repaint, and provide specific code examples. 1. What is CSS reflow? When the visibility, size or position of elements in the DOM structure changes, the browser needs to recalculate and apply CSS styles and then re-layout

The difference between __proto__ and prototype in JS The difference between __proto__ and prototype in JS Feb 19, 2024 pm 01:38 PM

__proto__ and prototype are two attributes related to prototypes in JS. They have slightly different functions. This article will introduce and compare the differences between the two in detail, and provide corresponding code examples. First, let’s understand what they mean and what they are used for. proto__proto__ is a built-in property of an object that points to the prototype of the object. Every object has a __proto__ attribute, including custom objects, built-in objects, and function objects. By __proto__ genus

See all articles