search
HomeWeb Front-endJS TutorialDetailed explanation of JavaScript event loop mechanism - Lecture 1

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);

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);
})()

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
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
Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

See all articles

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

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software