With the depth of JavaScript learning and the accumulation of practical experience, some principles and underlying things are beginning to be understood. I have seen some articles about JS single-threaded and event loops earlier, but at the time, indefinitely only left a general impression: The JS program in the browser is single-threaded. Well, that's a bit of an impression. There was also some doubt: since it was single-threaded, how was the asynchronous invocation implemented? Who is the timer to time the timer, this single-thread can not be executed on the side of the timing of the program? Why are those time-consuming I/O operations not blocking threads, not a good single thread? I believe a lot of students who do not know the JavaScript single thread have had similar questions.
Today saw a lot of relevant information, on a detailed summary of the hope to help everyone, at the same time they also comb a bit of knowledge, understanding is one thing, can write down is another thing. Okay, start the text.
One, JavaScript single thread
In the browser of a page, the page's JS program only one thread, so Yue single-threaded. Because it is a single thread, the execution order of the program is executed from top to bottom, and only one piece of code can be executed at a time. So why not multi-threading, so it's not better to take advantage of the CPU and improve efficiency?
Early Web content was very simple, single-threaded enough to handle, so at the beginning of the design, I guess the designers didn't think about using multithreading. In addition, JavaScript is mainly used to deal with the interaction between the user and the page, and the manipulation of the DOM, if the DOM is manipulated in a multithreaded way, one thread requires the DOM to be deleted, and the other requires the DOM style to be modified, so who should the browser listen to? This greatly increases the complexity of the program design, the front-end are not studious, is not ~ ~ ~ Simple how good.
Although JavaScript is single-threaded, the inside of the browser is not a single-threaded process. Some of your I/O operations, Timers and event snooping (click, KeyDown ... ) is done by other threads that are provided by the browser.
If you want to use multithreading to handle some time-consuming tasks, you can use the Web Worker presented by HTML5.
Second, task queue and event loop
Referring to the asynchronous mechanism, we have to talk about the task queue and event loop, here understand the main points of JS asynchronous mechanism.
To understand the concurrency model of the browser first, take a look at the following diagram:
The stack on the left is a synchronous task, and the so-called synchronous tasks are those that can be executed immediately, without time-consuming tasks, such as initialization of variables and functions, binding of events, and so on, which do not require callback functions. The heap on the right is used to store declared variables, objects. The following queue is the task queue, and once an asynchronous task responds, it is pushed into the queue. such as the user's Click event, the browser receives the response of the service and the settimeout inserted event that is mentioned later. Each asynchronous task is associated with a callback function.
A single thread of a JS program is used to perform synchronization tasks in the stack, when all synchronization tasks are completed, the stack is emptied, then a pending task in the task queue is read, and the related callback function is pressed into the stack, and the single thread starts to execute the new synchronization task and executes.
Single-threaded read tasks from the task queue are constantly looping, each time the stack is emptied, a new task is read in the task queue, and if there is no new task, it waits until there is a new task, which is called a task loop. Because each task is triggered by an event, it is also called an event loop.
Iii. Asynchronous mechanisms
With the above two sections to pave the understanding of the asynchronous mechanism is much easier. With Ajax, when a single thread of a page executes xhr.send() , the sending task is completed for the page. How to send, that is the browser thing, and single-threaded; When to respond, it is not to say. In order to get the content of the response in a timely manner, it is good to register the corresponding event in a single thread xhr.onreadystatechange = fn() {...} . Once registered, the browser automatically listens to the event for us in other threads inside. Until the event is triggered, the browser adds a task in the task queue to wait for the single thread to execute.
Four, timer
The function of settimeout is to insert the callback function into the task queue after a certain interval of time, and then execute after the synchronization tasks in the stack have been completed. Because the synchronization task in the stack is also time consuming, the interval is typically greater than or equal to the specified time.
setTimeout(fn, 0)This means that the callback function, FN, is immediately inserted into the task queue, waiting for execution instead of immediate execution. See an example:
SetTimeout (function () { console. Log ("a0) for(leti=0; I<10000; I+ +) {}console. Log ("b")//Result: b A
The printing results indicate that the callback function is not executed immediately, but that it waits for the task in the stack to execute. How long it will take for the task in the stack to be executed.
V. Summary
JavaScript is a single thread and its asynchronous mechanism is described above. The so-called single thread is not alone, it is behind the other threads of the browser for its service, its async also relies on other threads to listen to the response of the event, and push the callback function into the task queue to wait for execution. The single-threaded process is to execute the synchronization task in the stack, after execution, and then take an event from the task queue (no event, wait for the event), and then start to perform the related synchronization tasks in the stack, such as continuous loop.
Resources
- Concurrency model and Event Loop
- A detailed explanation of JavaScript running mechanism: Another talk about event Loop
- JavaScript async mechanism
JavaScript single-threaded and asynchronous mechanisms