Detailed explanation of javascript event loop mechanism examples
Javascript has a main thread main process and a call-stack (a call stack). When processing a task in a call stack, 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, The 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.
#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 in the browser kernel. Processing, the webkit kernel has an important module besides the Javasctipt execution engine, which 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.
First the execution context of the main() function is pushed onto the stack
Code Then execute, encounter 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.
When encountering setTimeout, the execution engine adds it to the stack.
The call stack found that setTimeout is the API in the WebAPIs mentioned before, so after popping it off the stack, the delayed execution function is handed over to the browser The timer module of the processor is processed.
The timer module handles delayed execution functions. At this time, the execution engine then executes and adds log('SJS') to the stack. This 'SJS' is output.
When the time specified by the delay method in the timer module is up, it is put into the task queue. At this time, the call stack All tasks have been executed.
After the task in the call stack is executed, the execution engine will then look at the execution task queue Is there a callback function that needs to be executed? 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
All code must be executed through calls in the function call stack.
When encountering the APIs mentioned in the previous article, it will be handed over to other modules of the browser kernel for processing.
The task queue stores callback functions.
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);
I found this code from an article on the Internet not long ago about JS interview questions that 80% of applicants failed. Now we Let’s analyze how this code outputs the final execution status 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;
First of all, 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 from the stack, the delayed execution function is handed over to the Timer module. deal with.
When i=1,2,3,4, the conditions are met. The situation is the same as when i=0. Therefore, there are 5 identical delayed execution functions in the timer module. .
When i=5, the condition is not met, so the for loop ends and console.log(new Date, i) is pushed onto the stack. At this time, i has become 5. So the output is 5.
At this time, 1s has passed, and the timer module returns the 5 callback functions to the task queue in the order of registration.
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.
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 over 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;
Related recommendations :
js event loop mechanism example analysis
The above is the detailed content of Detailed explanation of javascript event loop mechanism examples. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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

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

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

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

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: 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.

Golang is a powerful and efficient programming language that can be used to develop various applications and services. In Golang, pointers are a very important concept, which can help us operate data more flexibly and efficiently. Pointer conversion refers to the process of pointer operations between different types. This article will use specific examples to learn the best practices of pointer conversion in Golang. 1. Basic concepts In Golang, each variable has an address, and the address is the location of the variable in memory.

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
