Understanding synchronization and asynchronousness in js
The content shared with you in this article is about the understanding of synchronization and asynchronousness in js. It has certain reference value. Friends in need can refer to it
You should know that the javascript language is a The "single-threaded" language is not like the java language. The class inherits Thread and then uses thread.start to open a thread. Therefore, javascript is like an assembly line, just It’s just an assembly line, either processing or packaging, and cannot carry out multiple tasks and processes at the same time. So what are the
synchronous and asynchronous mentioned here? If you really don’t understand, I hope you read this article carefully. In fact, I personally feel that the official js documents are not accurate when using these two words, including many other words, which only sound sophisticated, but the actual application seems to have nothing to do with these words. For example, if you don't know the word "Event Delegation", who can tell what "Event Delegation" means at first glance? What event is delegated? What kind of delegation? I think it’s better to just call it “capture of events in outer elements”. Although it’s a little longer, you can understand it at once. Back on track, "synchronization" - the word "together" immediately makes people think of it; "asynchronous", literally speaking, seems to be doing something in different (different) ways, then The first word that comes to mind may be "while...while...", for example, 'Xiao Ming is eating ice cream and doing homework at the same time.' There is nothing wrong with this. After eating the ice cream, he also finished his homework. Is this asynchronous? That would be a big mistake!
In fact, synchronous and asynchronous, no matter what, there is only one pipeline (single thread) when doing things.
The difference between synchronous and asynchronous lies in the execution order of each process on this pipeline. different. The most basic asynchronous functions are setTimeout and setInterval functions, which are very common, but few people know that this is actually asynchronous, because they can control the execution order of js. We can also simply understand that operations that can change the normal execution sequence of the program can be regarded as asynchronous operations. The following code:
<script type="text/javascript"> console.log( "1" ); setTimeout(function() { console.log( "2" ) }, 0 ); setTimeout(function() { console.log( "3" ) }, 0 ); setTimeout(function() { console.log( "4" ) }, 0 ); console.log( "5" ); </script>
What is the output order?
It can be seen that although we set the waiting time in setTimeout(function, time) to 0, the function in it is still executed later.
The API document of Firefox browser has this sentence:
Because even thoughsetTimeout was
called with a delay of zero, it's placed on a queue and scheduled to run at the next opportunity, not immediately. Currently executing code must complete before functions on the queue are executed, the resulting execution order may not be as expected.
It means: Although the time delay time of setTimeout is 0, the function will also be put into a queue, waiting for the
to execute, the current code (referring to Programs that do not need to be added to the queue) must complete before the program in that queue completes, so the results may not be the same as expected. Here we talk about a "queue" (i.e. task queue). What is placed in the queue? What is placed in the queue is the function in setTimeout. These functions are added to the queue in turn, that is, among all the functions in the queue The program will be executed after all code outside the queue has been executed. Why is this? Because when executing a program, the browser will default to methods such as setTimeout and ajax requests as time-consuming programs (although they may not be time-consuming), and add them to a queue, which is a queue that stores time-consuming programs. , after all non-time-consuming programs are executed, the programs in the queue are executed in sequence.
Back to the original starting point-javascript is single-threaded. Single thread means that all tasks need to be queued, and the next task will not be executed until the previous task is completed. If the previous task takes a long time, the next task will have to wait. So there is a concept - task queue. If the queue is due to a large amount of calculation and the CPU is too busy, forget it, but many times the CPU is idle because the IO devices (input and output devices) are very slow (such as Ajax operations reading data from the network) and have to Wait for the results to come out before proceeding. So the designers of the JavaScript language realized that at this time, the main thread could completely ignore the IO device, suspend the waiting tasks, and run the later tasks first. Wait until the IO device returns the result, then go back and continue executing the suspended task.
So, all tasks can be divided into two types, one is synchronous task (synchronous) and the other is asynchronous task (asynchronous). Synchronous tasks refer to tasks queued for execution on the main thread. The next task can only be executed after the previous task is executed; asynchronous tasks refer to tasks that do not enter the main thread but enter the "task queue". Task, only when the main thread task is completed and the "task queue" starts to notify the main thread and request the execution of the task, the task will enter the main thread for execution.
Specifically, the asynchronous running mechanism is as follows:
(1) All synchronous tasks are on the main thread Execution, forming an execution context stack.
(2) In addition to the main thread, there is also a "task queue". As long as the asynchronous task has running results, an event is placed in the "task queue".
(3) Once all synchronization tasks in the "execution stack" are completed, the system will read the "task queue" to see what events are in it. Those corresponding asynchronous tasks end the waiting state, enter the execution stack, and start execution.
(4) The main thread continues to repeat the third step above.
As long as the main thread is empty, it will read the "task queue". This is the running mechanism of JavaScript. This process keeps repeating.
"Task queue" is an event queue (can also be understood as a message queue). When the IO device completes a task, an event is added to the "task queue" to represent related asynchronous The task can enter the "execution stack". The main thread reads the "task queue", which means reading the events in it.
The events in the "task queue", in addition to IO device events, also include some user-generated events (such as mouse clicks, page scrolling, etc.), such as $(selectot).click(function), these are A relatively time-consuming operation. As long as the callback functions of these events are specified, when these events occur, will enter the "task queue" and wait for the main thread to read.
The so-called "callback function" (callback) is the code that will be hung up by the main thread. The function in the click event $(selectot).click(function) mentioned earlier is a callback function. Asynchronous tasks must specify a callback function. When the main thread starts executing an asynchronous task, the corresponding callback function is executed. For example, ajax's success, complete, and error also specify their own callback functions. These functions will be added to the "task queue" and wait for execution.
Related recommendations:
js synchronization and asynchronous
JavaScript synchronization, asynchronous, callback execution sequence analysis
In-depth understanding of the synchronization and asynchronous mechanisms in JavaScript programming
The above is the detailed content of Understanding synchronization and asynchronousness in js. 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

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



Generally speaking, we only need to use one of the headphones or speakers at the same time. However, some friends have reported that in the win11 system, they encountered the problem of headphones and speakers sounding at the same time. In fact, we can turn it off in the realtek panel and it will be fine. , let’s take a look below. What should I do if my headphones and speakers sound together in win11? 1. First find and open the "Control Panel" on the desktop. 2. Enter the control panel, find and open "Hardware and Sound" 3. Then find the "Realtek High Definition" with a speaker icon. Audio Manager" 4. Select "Speakers" and click "Rear Panel" to enter the speaker settings. 5. After opening, we can see the device type. If you want to turn off the headphones, uncheck "Headphones".

When you find that one or more items in your sync folder do not match the error message in Outlook, it may be because you updated or canceled meeting items. In this case, you will see an error message saying that your local version of the data conflicts with the remote copy. This situation usually happens in Outlook desktop application. One or more items in the folder you synced do not match. To resolve the conflict, open the projects and try the operation again. Fix One or more items in synced folders do not match Outlook error In Outlook desktop version, you may encounter issues when local calendar items conflict with the server copy. Fortunately, though, there are some simple ways to help

A very useful function of win10 clipboard is the cross-device cloud storage function, which is very useful and can help users copy and paste simultaneously on PC devices and mobile devices. The setting method is very simple, just set it on the clipboard in the system. Synchronize win10 clipboard to mobile phone 1. First click Start in the lower left corner to enter settings. 2. Then click "System". 3. Select "Clipboard" on the left. 4. Finally, click Login in "Cross-device synchronization" on the right, and then select your mobile phone.

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

Concurrent and Asynchronous Programming Concurrent programming deals with multiple tasks executing simultaneously, asynchronous programming is a type of concurrent programming in which tasks do not block threads. asyncio is a library for asynchronous programming in python, which allows programs to perform I/O operations without blocking the main thread. Event loop The core of asyncio is the event loop, which monitors I/O events and schedules corresponding tasks. When a coroutine is ready, the event loop executes it until it waits for I/O operations. It then pauses the coroutine and continues executing other coroutines. Coroutines Coroutines are functions that can pause and resume execution. The asyncdef keyword is used to create coroutines. The coroutine uses the await keyword to wait for the I/O operation to complete. The following basics of asyncio

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

How to synchronize Baidu Cloud Sync Disk? You can select files to synchronize in Baidu Cloud Sync Disk, but most users don’t know how to synchronize Baidu Cloud files. Next is the graphic tutorial of Baidu Cloud Sync Disk synchronization method brought by the editor for users. Interested users come and take a look! How to synchronize Baidu Cloud Sync Disk 1. First enter the computer desktop, right-click the [Baidu Cloud Sync Disk] icon and select [Settings]; 2. Then expand the service window, switch to the [Advanced Settings] page and click [Select Folder]; 3. Finally switch to the page as shown below, check the files that need to be synchronized and click [OK].

Locks and Synchronization in Concurrent Programming In concurrent programming, multiple processes or threads run simultaneously, which can lead to resource contention and inconsistency issues. To solve these problems, locks and synchronization mechanisms are needed to coordinate access to shared resources. Concept of Lock A lock is a mechanism that allows only one thread or process to access a shared resource at a time. When one thread or process acquires a lock, other threads or processes are blocked from accessing the resource until the lock is released. Types of locks There are several types of locks in python: Mutex lock (Mutex): ensures that only one thread or process can access resources at a time. Condition variable: Allows a thread or process to wait for a certain condition and then acquire the lock. Read-write lock: allows multiple threads to read resources at the same time, but only allows one thread to write resources
