


Detailed explanation of the characteristics of JS single-threaded asynchronous io callback
Most of our initial contact with JavaScript started with js scripts in HTML. However, we have been using this seemingly simple language for several years, and we have not yet understood some of its principles and mechanisms. Are there any mistakes? At least JavaScript uses various event callbacks when operating DOM, such as button, link click, mouse passing, focus acquisition, etc. This article mainly analyzes the characteristics of JavaScript single-threaded asynchronous io callbacks. I hope that the content we have compiled can Help you.
In this process, we bind an event callback function on the dom such as onclick="doCheck()" This process is to register a click event for the dom element and bind an event callback function doCheck ().
When the mouse clicks on this element, an event is triggered, and the event binding function is immediately executed and returned.
Later, when I came into contact with jquery, a large number of
$("#id").click(function(){ alert('点击事件'); });
I seem to be used to this jquery syntax as I write more and more, but you have noticed that the previous selector only selects and filters the dom node, and the subsequent click is a Event registration, and the function(){} inside is actually a parameter, the parameter of the event binding function, which requires you to be familiar with the syntax of javascript.
function is an object in javascript, and the object is It can refer to everything in the world, so objects can contain many attributes, methods, etc.
Since it is an object, it can be passed as a parameter. This kind of function is called a higher-order function.
And this kind of function doesn’t have a defined name, right? Of course you can give it a name, and it’s the same thing if you pass the name over, but it’s meaningless because the function object here is actually a formal parameter, so we are used to not giving this kind of function a name. Name, this is what is often called an anonymous function.
Following the $("#id").click above, when the click event is triggered, the event binding function must be executed. Directly with the above The onclick method given on the DOM has the same effect.
Assume that there are multiple threads in the browser to operate the script, can you imagine the chaos? Thread 1 is about to modify the value of element A , but I didn’t expect that thread two had already deleted element A from the DOM tree. At this time, thread one failed to operate and reported an error. This situation is not terrible. Either the browser fails to maintain the consistency of data across multiple threads, or the front-end engineer Maintain it yourself, so... the browser only has one thread to operate the dom, which saves a lot of unnecessary trouble.
setTimeout(function(){ alert('弹出'); },300); while(true){ ........ }
Do you think 300 milliseconds Is there any drama after alert('pop-up')?
No, there will never be drama. Waiting for 300 milliseconds is just to deceive your emotions. Because the browser executes the script in single-thread mode.
Once the thread is in infinite loop mode and executes the while statement, your setTimeout will no longer have any effect.
Then we enter the node.js world, which completely retains the characteristics of javascript in the browser , single-threaded asynchronous callback, it is precisely because of this feature that it is what it is. If node.js is a synchronous language, even if all npm packages are extended by c++ (the speed is fast enough), no matter how fast you are, you can't beat c. Language processing speed, then node.js may have been despised by PHP before it was born.
It is precisely because of its asynchronous callback IO that it can improve its efficiency, which reminds me of a student from my previous school. A comparison between a fast food restaurant and a school cafeteria:
In the cafeteria, all the students lined up in a line at the window with their plates. The sister who prepared the meal filled it one by one, and then left with the rice one by one. This is It is the result of synchronous processing.
School fast food restaurants also have students queuing up to order, but after ordering, you can take your pager and leave to find a seat. In this way, the waiter can provide services to many people within a unit time. Moreover, students who have ordered a meal can find a seat to do other things on their own, instead of standing stupidly at the window waiting for the meal. The moment your meal comes out, the server will press the code according to the order number, and then the call on your table will The caller will ring, and you can just go and get the meal. This is asynchronous processing. When the caller sounds, it triggers an event.
Single thread can reduce resource waste and maintenance difficulties caused by status switching between multiple threads. Of course, There are also specialized third-party packages to support multi-core and multi-thread scenarios, you can weigh it yourself.
Related recommendations:
Single-threaded setTimeout in JavaScript
How the single-threaded programming language PHP implements multi-threaded operations
Introduces in detail some things about JavaScript single-threading (picture)
The above is the detailed content of Detailed explanation of the characteristics of JS single-threaded asynchronous io callback. For more information, please follow other related articles on the PHP Chinese website!

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.

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.

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.


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

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

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

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

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

Dreamweaver CS6
Visual web development tools