Understanding the single thread and javascript Timer In the javascript Timer

Source: Internet
Author: User

Understanding the single thread and javascript Timer In the javascript Timer

1. the JavaScript engine is single-threaded.

We can see from the following code that the first code in setTimeout is an endless loop. Because it is a single thread, the following two timers will not be able to be executed.

<Script type = "text/javascript"> setTimeout (function () {while (true) {}}, 100); setTimeout (function () {alert ('Hello! SetTimeout ') ;}, 200); setInterval (function () {alert ('Hello! Setinterval') ;}, 200); </script>

The browser kernel is multi-threaded. They work with each other under the kernel control to maintain synchronization. A browser implements at least three resident threads: javascript Engine threads, GUI rendering threads, and browser event triggering threads.

The JavaScript engine is based on the event-driven single-thread execution. The JS engine is waiting for the arrival of tasks in the task queue to be processed, the browser has only one JS thread running the JS program at any time.
The GUI rendering thread is responsible for rendering the browser interface. When the interface needs to be repainted or reflow is triggered due to some operation, this thread will execute. However, you must note that the GUI rendering thread and JS engine are mutually exclusive. When the JS engine is executed, the GUI thread will be suspended, GUI updates are saved in a queue and executed immediately when the JS engine is idle.
Browser event triggering thread. When an event is triggered, the thread adds the event to the end of the queue to be processed, waiting for processing by the JS engine. These events can come from the code blocks currently executed by the JavaScript engine, such as setTimeOut, other threads from the browser kernel, such as mouse clicks and AJAX asynchronous requests, however, because of the single-threaded relationship of JS, all these events have to be queued for processing by the JS engine.

It can be seen that the JavaScript engine in the browser is event-driven. The event here can be seen as a variety of tasks sent to it by the browser. the JavaScript engine has been waiting for the arrival of tasks in the task queue, due to the single-threaded 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.

T1 time:

1. GUI rendering thread
2. browser event trigger thread:

During the t1 period, the user clicks a mouse key and a mouse clicking event is triggered by a browser event to capture the mouse clicking event. The figure shows that for the JavaScript engine thread, this event is asynchronously uploaded to the end of the task queue by other threads. Because the engine is processing the task at t1, the mouse click event is waiting for processing.
3. Scheduled thread triggering:
The browser model timing counters here are not counted by the JavaScript engine, because the JavaScript engine is single-threaded and cannot be counted if it is in the congested thread state, it depends on external timing and triggers timing. Therefore, scheduled events in the queue are asynchronous events.
4. During this t1 period, after the mouse click event is triggered, the previously set setTimeout time has also arrived. For the JavaScript engine, the scheduled trigger thread generates an asynchronous scheduled event and stores it in the task queue. This event is scheduled to wait for processing after the Click Event Callback. Similarly, in the t1 period, a setInterval timer is also added. Due to the interval, the timer is triggered twice consecutively in the t1 segment, these two events are arranged at the end of the Team for processing.
5. ajax asynchronous requests:
The browser opens an http thread request. When the Request status changes, if a callback has been set previously, This asynchronous thread will generate a state change event and place it in the processing queue of the JavaScript engine for medium waiting for processing.
2. Different tasks are executed in different sequence, and different results are displayed.

1) the setTimeout function is not used.

A code instance found on the Internet. It is used for demonstration here.

<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 wait... '; sleep (3000); // simulate a time-consuming computing process, 3 s status. innerHTML = 'done'; return false ;}; </script>

I executed the above Code in firefox. Click "do something", then "doing... please wait..." is displayed, sleep is executed, and "done" is displayed ".

However, after clicking the button, the browser gets stuck for about 3 seconds and the done is displayed directly.

The analysis shows that status is being performed. when innerHTML is set, the GUI rendering thread needs to be executed, but the JavaScript engine thread is still being executed, while the JavaScript engine thread and the GUI rendering thread are mutually exclusive, so done is displayed.

2) the setTimeout function is used.

<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 wait...';    setTimeout(function() {   sleep2(3000);    status2.innerHTML = 'done';    }, 100);    return false;  };</script>

In "doing... please wait... "followed by a setTimeout, delayed execution, giving the browser rendering time, this will show" doing... please wait... then run the sleep function and display "done ".

Later, some Web friends did not work in firefox. I modified the code and put the declaration of local variables and the onclick binding to the window. in the onload event, after the page structure is loaded, I will perform the script operation again.

<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 all the content of this article, hoping to help you learn.

Articles you may be interested in:
  • When getting the focus, use the js timer to set the time to execute the action
  • JS timer instance
  • Javascript/Jquery-various implementation methods of simple Timer
  • JavaScript timer details and examples
  • How to Write a js timer? Is to execute a program at a specific time.
  • Js timer setTimeout cannot call local variable solution
  • Js timer usage (example)
  • Js timer (executed once and repeatedly)
  • Nodejs simple getting started tutorial (2): Timer
  • Difference between the timer nextTick () and setImmediate () in node. js

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.