


Detailed explanation of the working mechanism of javascript asynchronous processing_javascript skills
From a basic level, it is very important to understand how JavaScript timers work. The execution of timers is often different from our intuitive imagination. That is because the JavaScript engine is single-threaded. Let's first understand how the following three functions control timers.
var id = setTimeout(fn, delay); - Initialize a timer and then execute it after the specified time interval. This function returns a unique flag ID (Number type) that we can use to cancel the timer.
var id = setInterval(fn, delay); - Somewhat similar to setTimeout, but it continuously calls a function (the time interval is the delay parameter) until it is canceled.
clearInterval(id);, clearTimeout(id); - Use the timer ID (the return value of setTimeout and setInterval) to cancel the occurrence of the timer callback
In order to understand the inner workings of timers, there is an important concept that needs to be discussed: timer delays are not guaranteed. Since all JavaScript code is executed in a thread, all asynchronous events (such as mouse clicks and timers) will only execute when they have a chance to execute.
There is a lot of information to understand in this diagram, and if you fully understand it, you will have a good understanding of how the JavaScript engine implements asynchronous events. This is a one-dimensional icon: the vertical direction represents time, and the blue blocks represent JavaScript code execution blocks. For example, the first JavaScript code execution block takes about 18ms, the code execution block triggered by a mouse click takes 11ms, and so on.
Since the JavaScript engine only executes one code at a time (this is due to the single-threaded nature of JavaScript), each JavaScript code execution block will "block" the execution of other asynchronous events. This means that when an asynchronous event occurs (for example, a mouse click, a timer is triggered, or an Ajax asynchronous request), the callback functions of these events will be queued at the end of the execution queue waiting to be executed (actually, the queuing method depends on the browser It varies depending on the device, so this is just a simplification);
Start studying from the first JavaScript execution block, in which two timers are initialized: a 10ms setTimeout() and a 10ms setInterval(). Depending on when and where the timer is initialized (it will start counting after the timer is initialized), the timer will actually be triggered before the first code block completes execution. However, the function bound to the timer will not be executed immediately (the reason why it is not executed immediately is that JavaScript is single-threaded). In fact, the delayed functions will be queued at the end of the execution queue, waiting for the next appropriate time to execute.
In addition, in the first JavaScript execution block we see that a "mouse click" event occurs. A JavaScript callback function is bound to this asynchronous event (we never know when the user executes this (click) event, so it is considered asynchronous). This function will not be executed immediately, like the timer above, It will be queued at the end of the execution queue, waiting for execution at the next appropriate time.
When the first JavaScript execution block is executed, the browser will immediately ask a question: Which function (statement) is waiting to be executed? At this time, a "mouse click event handler function" and a "timer callback function" are waiting to be executed. The browser will select one (actually select the "handler function for mouse click event", because it can be seen from the picture that it is queued first) and execute it immediately. The "timer callback function" will wait for the next appropriate time to execute.
Note that when the "mouse click event handler function" is executed, the setInterval callback function is triggered for the first time. Like the setTimeout callback function, it will be queued to the end of the execution queue and wait for execution. However, be sure to pay attention to this: when the setInterval callback function is triggered for the second time (the setTimeout function is still executing at this time) the first triggering of setInterval will be discarded. When a long code block is executed, all setInterval callback functions may be queued at the back of the execution queue. After the code block is executed, the result will be a large series of setInterval callback functions waiting to be executed, and between these functions No intervals until it's all done. Therefore, browsers tend to queue the next handler to the end of the queue when there are no more interval handlers in the queue (this is due to the interval issue).
We can find that when the third setInterval callback function is triggered, the previous setInterval callback function is still executing. This illustrates a very important fact: setInterval does not consider what is currently being executed, but queues all blocked functions to the end of the queue. This means that the time interval between two setInterval callback functions will be sacrificed (reduced).
Finally, when the second setInterval callback function is executed, we can see that there is no program waiting for the JavaScript engine to execute. This means that the browser is now waiting for a new asynchronous event to occur. At 50ms, a new setInterval callback function is triggered again. At this time, no execution block blocks its execution. So it will be executed immediately.
Let us use an example to clarify the difference between setTimeout and setInterval:
setTimeout ( function ( ) { /* Some long block of code... */ setTimeout (arguments. callee, 10 ); }, 10 ); setInterval ( function ( ) { /* Some long block of code... */ }, 10 );
These two lines of code may not seem to differ at first glance, but they are different. The interval between the execution of the setTimeout callback function and the previous execution is at least 10ms (maybe more, but not less than 10ms), while the setInterval callback function will try to execute every 10ms, regardless of whether the last execution is completed.
We have learned a lot here, to summarize:
The JavaScript engine is single-threaded, forcing all asynchronous events to be queued for execution
There are fundamental differences between setTimeout and setInterval when executing asynchronous code
If a timer is blocked and cannot be executed immediately, it will delay execution until the next possible execution time point (which is longer than the expected time interval)
If the execution time of the setInterval callback function will be long enough (longer than the specified time interval), they will be executed continuously and without a time interval between each other.
The above is the entire content of this article. I hope it will be helpful to everyone in learning javascript asynchronous processing.

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

AI Hentai Generator
Generate AI Hentai for free.

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



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

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

How to debug async processing issues in PHP functions? Use Xdebug to set breakpoints and inspect stack traces, looking for calls related to coroutines or ReactPHP components. Enable ReactPHP debug information and view additional log information, including exceptions and stack traces.

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

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

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