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!

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base


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

Atom editor mac version download
The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

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.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft