Understanding single-threaded _javascript techniques in JavaScript timers

Source: Internet
Author: User
Tags setinterval sleep function

One, the JavaScript engine is single-threaded

As you can see from the following code, the first code in settimeout is a dead loop, and since it is single-threaded, the following two timers have no chance of executing.

<script type= "Text/javascript" >
 settimeout (function () {while (true) {}}; 
 settimeout (function () {alert (' Hello!settimeout '); 
 SetInterval (function () {alert (' Hello!setinterval '); 
</script>

The browser's kernel is multi-threaded, they work together in a kernel system to keep synchronization, and a browser implements at least 3 resident threads: JavaScript engine thread, GUI rendering thread, browser event triggering thread.

JavaScript engine is based on event-driven single-threaded execution, JS engine has been waiting for the task queue in the arrival of the task and then processed, the browser no matter what time there is only a JS thread running the JS program.
The GUI rendering thread is responsible for rendering the browser interface, which is executed when the interface needs to be redrawn (Repaint) or because of an operation that causes Backflow (reflow). But note that the GUI rendering thread is mutually exclusive with the JS engine, and when the JS engine executes, the GUI thread is suspended, and the GUI update is saved in a queue until the JS engine is idle and executed immediately.
A browser event triggers a thread that, when triggered, adds an event to the tail of the queue to be processed and waits for the JS engine to process it. These events can come from code blocks currently executed by the JavaScript engine such as settimeout, other threads from the browser kernel such as mouse clicks, Ajax asynchronous requests, and so on, but because of JS's single-threaded relationships All of these events have to be queued for JS engine processing.

As you can see from the illustration above, the JavaScript engine in the browser is event-based, and the event can be seen as a variety of tasks that the browser sends to it, and the JavaScript engine waits for tasks in the task queue, which have to be queued due to single-threaded relationships, One after another is processed by the engine.

T1, t2....tn represent different points in time, TN the corresponding small squares represent the task at that point in time.

T1 moment:

1. GUI Rendering thread
2. Browser Event Trigger Thread:

Within the T1 time period, first, the user clicked a mouse button, click on the browser event triggered by the thread capture after the formation of a mouse click event, from the diagram that, for JavaScript engine thread said, this event is the other thread to the end of the task queue asynchronous, because the engine is processing T1 tasks, This mouse click event is waiting to be processed.
3, timing trigger thread:
The browser model timer counter here is not counted by the JavaScript engine, because the JavaScript engine is single-threaded and, if it cannot be counted in a blocked thread state, it must rely on external timing and trigger timing, so the timed event in the queue is an asynchronous event.
4, in this T1 time period, after the mouse click event is triggered, the previously set settimeout timer arrives, and at the moment for the JavaScript engine, the timed trigger thread generates an asynchronous timed event and puts it in the task queue, which is queued to be processed after the click event callback. Similarly, in the T1 time period, the next setinterval timer was added, due to the interval timing, in the T1 segment was triggered two consecutive times, the two events were queued to the end of the queue to be processed.
5. Ajax Asynchronous Request:
The browser opens a new HTTP thread request, and when the requested state changes, if the callback was previously set, the asynchronous thread waits for processing in the JavaScript engine's processing queue for the resulting state change event.
The execution order of the task is different, the display result is different

1 does not use the SetTimeout function

An example of a code found on the web, used here to demonstrate.

<a href= "#" id= "dobtn" >do something</a> <div id=
"status" ></div>
<script type= " Text/javascript ">
  var dobtn = document.getElementById (' dobtn ')
   , status = document.getElementById (' Status ');

  function Sleep (ms) {
  var start = new Date ();
  while (new Date ()-Start <= ms) {}
  }
  
  Dobtn.onclick = function (e) {
   status.innerhtml = ' Doing...please Wai t ... '; 
   Sleep (3000); Simulate a time-consuming computational process, 3s
   status.innerhtml = ' done '; 
   return false;
</script>

I executed the above code in Firefox. The plan is to click on the "Do something" button and then show "Doing...please wait ...", then perform sleep and finally show "done".

But the result is that after clicking, the browser is stuck for about 3 seconds, and finally shows the done directly.

The analysis shows that when making the status.innerhtml setting, it is necessary to perform the GUI rendering thread, but it is still executing the JavaScript engine thread, and the JavaScript engine thread is mutually exclusive with the GUI rendering thread, so it is finally shown done.

2) using the SetTimeout function

<a href= "#" id= "doBtn2" >do something timer</a> <div id=
"Status2" ></div>
<script Type= "Text/javascript" >
  var doBtn2 = document.getElementById (' doBtn2 ')
   , Status2 = document.getElementById (' Status2 ');

  function Sleep2 (ms) {
  var start = new Date ();
  while (new Date ()-Start <= ms) {}
  }
  
  Dobtn2.onclick = function (e) {
   status2.innerhtml = ' Doing...please w Ait ... '; 
   settimeout (function () {
   SLEEP2 (3000); 
   status2.innerhtml = ' done '; 
   return false;
</script>

In the "Doing...please wait ..." followed by a settimeout, delay execution, give the browser rendering time, this time will show "doing...please ..." words, and then execute the sleep function, and finally show " Done. "

Behind a netizen found in Firefox does not work, indeed there is this problem, I modified the code, the local variables of the statement, onclick binding to the Window.onload event, and so on page structure after loading, I do script operation.

<script type= "Text/javascript" >
  function Sleep (ms) {
  ///...
  }
  Window.onload = function () {
   var dobtn = document.getElementById (' dobtn '),
   status = document.getElementById (' Status ');
   
   var doBtn2 = document.getElementById (' doBtn2 ')
    , status2 = document.getElementById (' Status2 ');
    
   Dobtn.onclick = function (e) {
    //...
   };
   Dobtn2.onclick = function (e) {
    //...
   };
  };
</script>

The above is the entire content of this article, I hope to help you learn.

Related Article

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.