


For example,
setTimeout( function(){ alert('Hello !'); } , 0);
setInterval( callbackFunction , 100);
It is believed that the greeting method in setTimeout will be executed immediately, because this is not said out of thin air, but JavaScript The API document clearly defines the meaning of the second parameter as the number of milliseconds after which the callback method will be executed. If it is set to 0 milliseconds, of course it will be executed immediately.
Similarly, the callbackFunction method of setInterval will be executed every 100 milliseconds. You have no doubt that it will be executed immediately!
But as your JavaScript application development experience continues to increase and enrich, one day you find a strange piece of code and you are puzzled:
div.onclick = function(){
setTimeout( function(){document.getElementById ('inputField').focus();}, 0);
};
Since it is executed after 0 milliseconds, why use setTimeout? At this moment, the firm belief has begun to waver. .
Until the last day, you accidentally wrote a piece of bad code:
setTimeout( function(){ while(true){} } , 100);
setTimeout( function(){ alert('Hello!'); } , 200);
setInterval( callbackFunction , 200);
The first line of code enters an infinite loop, but soon you will find that the second and third lines are not what you expected, the alert greeting does not appear, and there is no news from the callbacKFunction!
At this time, you are completely confused. This situation is difficult to accept, because the process of changing the long-established cognition to accept new ideas is painful, but the facts are before you, and the search for the truth of JavaScript will not be because of pain. And stop, let us start the journey of exploring JavaScript threads and timers!
Open the clouds and see the moonlight
The main reason for all the above misunderstandings is: subconsciously believing that, The JavaScript engine has multiple threads executing, and the timer callback function of JavaScript is executed asynchronously.
In fact, JavaScript uses a blinding method to deceive our eyes most of the time. The backlight needs to be clarified here. A fact:
The JavaScript engine runs in a single thread, and the browser has only one thread running the JavaScript program at any time.
It also makes sense for the JavaScript engine to run in a single thread. , a single thread does not have to worry about complex issues such as thread synchronization, and the problem is simplified.
So how does the single-threaded JavaScript engine cooperate with the browser kernel to process these timers and respond to browser events?
The following A brief explanation combined with the browser kernel processing method.
The browser kernel implementation allows multiple threads to execute asynchronously. These threads cooperate with each other under kernel control to maintain synchronization. If a browser kernel has at least three implementations Resident threads: JavaScript engine threads, interface rendering threads, browser event triggering threads. In addition to these, there are also some threads that terminate after execution, such as HTTP request threads. These asynchronous threads will generate different asynchronous events. Here is a picture To illustrate how the single-threaded JavaScript engine interacts and communicates with other threads. Although the implementation details of each browser kernel are different, the calling principles are similar.

As you can see from the picture It turns out that the JavaScript engine in the browser is event-driven. The events here can be regarded as various tasks assigned to it by the browser. These tasks can originate from the code block currently executed by the JavaScript engine, such as calling setTimeout to add a task. , can also come from other threads in the browser kernel, such as interface element mouse click events, scheduled trigger time arrival notifications, asynchronous request status change notifications, etc. From a code perspective, task entities are various callback functions, and the JavaScript engine has been waiting The arrival of tasks in the task queue. Due to the single-thread relationship, these tasks have to be queued and processed by the engine one after another.
The above figure t1-t2..tn represents different time points, and the corresponding small ones below tn The box represents the task at that time point. Assume that it is time t1 and the engine is running in the task block code corresponding to t1. At this point in time, let us describe the status of other threads in the browser kernel.
t1 Time:
GUI rendering thread:
This thread is responsible for rendering the HTML elements of the browser interface. When the interface needs to be redrawn (Repaint) or a reflow is caused by some operation, this thread will be executed. Although this article focuses on explaining the JavaScript timing mechanism, it is necessary to talk about the rendering thread at this time, because this thread and the JavaScript engine thread are mutually exclusive. This is easy to understand, because JavaScript scripts can manipulate DOM elements. When modifying these If the element attributes render the interface at the same time, the element data obtained before and after the rendering thread may be inconsistent.
While the JavaScript engine is running the script, the browser rendering thread is in a suspended state, which means it is "frozen" ”.
Therefore, updates to the interface performed in the script, such as adding nodes, deleting nodes, or changing the appearance of nodes, will not be reflected immediately. These operations will be saved in a In the queue, the JavaScript engine will have the opportunity to render when it is idle.
GUI event triggering thread:
The execution of JavaScript scripts does not affect the triggering of html element events. During the t1 time period, first The user clicks a mouse button. The click is captured by the browser event trigger thread and forms a mouse click event. As can be seen from the figure, for the JavaScript engine thread, this event is asynchronously transmitted to the end of the task queue by other threads. Since the engine The task at t1 is being processed, and this mouse click event is waiting to be processed.
Timing trigger thread:
Note that the browser model timing counter here is not counted by the JavaScript engine, because the JavaScript engine It is single-threaded. If it is in the blocked thread state, it cannot count the time. It must rely on the outside to time and trigger the timing, so the timing events in the queue are also asynchronous events.
As can be seen from the picture, at the time of t1 Within the segment, after the mouse click event is triggered, the previously set setTimeout timing has also arrived. At this moment, for the JavaScript engine, the timing trigger thread generates an asynchronous timing event and puts it in the task queue. The event is queued to the click event. After the callback, wait for processing.
Similarly, still in the t1 period, a setInterval timer is also added next. Because it is interval timing, it is triggered twice in a row in the t1 period. These two The event is queued to the end of the queue to be processed.
It can be seen that if the time period t1 is very long, much larger than the timing interval of setInterval, then the timing trigger thread will continuously generate asynchronous timing events and put them at the end of the task queue regardless of whether they have been processed, but once t1 and the first After the tasks in front of the scheduled event have been processed, the scheduled events in these arrangements will be executed one after another without interruption. This is because, for the JavaScript engine, each task in the processing queue is processed in the same way. The order is just different.
After t1, that is to say, the currently processed task has been returned, the JavaScript engine will check the task queue, and if it finds that the current queue is not empty, it will take out the corresponding task under t2 for execution, and so on at other times. , from this point of view:
If the queue is not empty, the engine will take out a task from the head of the queue until the task is processed, that is, after returning, the engine will then run the next task. Before the task returns, the engine will Other tasks cannot be executed.
I believe you now have a clear understanding of whether JavaScript can be multi-threaded, and also understand the JavaScript timer operating mechanism. Let’s analyze some cases:
Case 1: setTimeout and setInterval
setTimeout(function( ){
/* Code block... */
setTimeout(arguments.callee, 10);
}, 10);
setInterval(function(){
/ *Code block... */
}, 10);
These two pieces of code look the same together, but they are not. The setTimeout in the callback function in the first paragraph is the JavaScript engine. After execution, set a new setTimeout timing. Assume that there is a time interval from the completion of the previous callback processing to the start of the next callback processing. Theoretically, the execution time interval of two setTimeout callbacks >= 10ms. The second period is triggered regularly after the setInterval is set. The thread will continuously generate asynchronous timing events every ten seconds and put them at the end of the task queue. Theoretically, the execution time interval between two setInterval callbacks is
Case 2: ajax asynchronous request Is it really asynchronous?
Many classmates and friends are confused. Since JavaScript is said to run in a single thread, is XMLHttpRequest really asynchronous after connecting?
In fact, the request is indeed asynchronous. However, this request is made by the browser to open a new thread (see the picture above). When the status of the request changes, if a callback has been set previously, the asynchronous thread will generate a status change event and put it in the JavaScript engine's processing queue to wait for processing. When a task is processed, the JavaScript engine always runs the callback function in a single thread, specifically the function set by onreadystatechange in a single thread.

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr


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

SublimeText3 Linux new version
SublimeText3 Linux latest version

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

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

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.
