Exploring the cloud and seeing the JavaScript timing mechanism in the Moon (1)

Source: Internet
Author: User

The setTimeout and setInterval of JavaScript are two methods that can easily fool "others' feelings", because we often think that the call will be executed in the established way. I think many people share the same feeling, for example:

BKJIA recommended reading: 12 traps to be bypassed in JavaScript syntax

 
 
  1. SetTimeout (function () {alert ('Hello! ');}, 0 );
  2. SetInterval (callbackfunctions, 100 );

It is assumed that the greeting method in setTimeout will be executed immediately, because it is not just a thin air, but the JavaScript API documentation clearly defines the second parameter meaning how many milliseconds later, the callback method is executed. it is set to 0 ms, and it is a matter of course immediately executed. Similarly, I believe that the setInterval callbackFunction method is executed immediately at an interval of 100 milliseconds! However, as JavaScript Application Development experiences continue to increase and enrich, one day you may find a piece of weird code that cannot be understood:

 
 
  1. div.onclick = function(){  
  2. setTimeout( function()  
  3. {document.getElementById(’inputField’).focus();}, 0);  
  4. }; 

Since it was executed after 0 milliseconds, what are setTimeout? At this moment, the firm belief has begun to shake, until the last day, you accidentally wrote a piece of bad code:

 
 
  1. SetTimeout (function () {while (true) {}}, 100 );
  2. SetTimeout (function () {alert ('Hello! ');}, 200 );
  3. SetInterval (callbackfunctions, 200 );

The first line of code is in an endless loop, but soon you will find that the second and third lines are not unexpected. alert greetings are not displayed, and callbacKFunction has no news! At this moment, you are completely confused. This kind of situation is unacceptable, because it is painful to change the long-established cognitive process to accept new ideas, but the fact is at present, the Exploration of JavaScript truth will not stop because of the pain. Let's start exploring JavaScript threads and timers next!

One of the main reasons for all the mistakes above is that the subconscious thinks that the JavaScript engine has multiple threads to execute, and the JavaScript timer callback function is executed asynchronously. In fact, javaScript uses the blind eye method, and most of the time we have cheated our eyes. Here, the backlights need to clarify the fact:

The JavaScript engine runs in a single thread. At any time, the browser only has one thread running JavaScript programs.

It is also meaningful for the JavaScript engine to run with a single thread. A single thread does not need to care about the complicated issues of thread synchronization, which simplifies the problem. so how does the single-threaded JavaScript Engine work with the browser kernel to process these timers and respond to browser events? The following is a brief description of the browser kernel processing method.

The browser kernel implementation allows multiple threads to run asynchronously. These threads work with each other under kernel control to maintain synchronization. if a browser kernel has at least three resident threads: javascript Engine threads, interface rendering threads, and browser event triggering threads, there are also some threads that terminate upon execution, such as the Http request thread, which will generate different asynchronous events, the following figure illustrates how the JavaScript engine of a single thread interacts with other threads. although the implementation details of each browser kernel are different, the calling principle is similar.

As shown in the figure, the JavaScript engine in the browser is event-driven. Events here can be seen as various tasks sent to it by the browser. These tasks can be derived from the code block currently executed by the JavaScript engine, for example, if you call setTimeout to add a task, you can also use other threads in the browser kernel, such as interface elements, mouse-click events, scheduled trigger time arrival notifications, and asynchronous request status change notifications. from the code point of view, the task entity is a variety of callback functions, and the JavaScript engine has been waiting for the arrival of tasks in the task queue. because of the single-thread relationship, these tasks must be queued and processed by the engine one after another.

T1-t2 .. tn indicates different time points, and the corresponding small blocks under tn represent the tasks at this time point. For example, if the time is t1, the engine runs in the task block code corresponding to t1, at this time point, we will describe the status of other threads in the browser kernel.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.