JavaScript timer (one)--single thread

Source: Internet
Author: User
Tags setinterval sleep function

One, the JavaScript engine is single thread

As can be seen from the code below, the first code in settimeout is a dead loop, because it is a single thread, the following two timers will not be able to execute.

<Scripttype= "Text/javascript">SetTimeout (function(){  while(true){} } ,  -); SetTimeout (function() {alert ('Hello,!settimeout .'); } ,  $); SetInterval (function() {alert ('Hello,!setinterval .'); }  ,  $); </Script>

The kernel of the browser is multi-threaded, and they mate with each other in the kernel to keep in sync, and a browser implements at least 3 resident threads: JavaScript engine thread, GUI render thread, browser event trigger thread.

    1. JavaScript engine is based on the event-driven single-threaded execution, the JS engine has been waiting for tasks in the task queue to come and then to deal with, the browser no matter when there is only one JS thread running JS program.
    2. The GUI rendering thread is responsible for rendering the browser interface, which executes when the interface needs to be redrawn (Repaint) or when a return (reflow) is caused by an operation. However, it is important to note that the GUI rendering thread is mutually exclusive to 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.
    3. The browser event triggers the thread, and when an event is triggered the thread adds the event to the end of the queue to be processed and waits for the JS engine to process. These events can come from code blocks currently executing 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 the JS single-threaded relationship all of these events are queued for the JS engine to process .

As can be seen, the JavaScript engine in the browser is event-driven, where the event can be seen as a variety of tasks that the browser sent it, the JavaScript engine has been waiting for the task queue of the arrival of tasks, because of single-threaded relationship, these tasks have to be queued, one after another by the engine processing.

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

t1 moment:

    1. gui render thread
    2. browser Event Trigger thread:

    3. timed trigger thread:

    4. ajax asynchronous Request:

      The browser opens a new HTTP thread request, and when the state of the request changes, if a callback has been set previously, the asynchronous thread will produce a state change event to be placed in the processing queue of the JavaScript engine for processing.
Second, the order of execution of the task is different, the display result is also different

1) settimeout function not used

A snippet of code found on the web is used here to illustrate.

<ahref="#"ID= "Dobtn">Do something</a><DivID= "status"></Div><Scripttype= "Text/javascript">      vardobtn=document.getElementById ('dobtn'), Status=document.getElementById ('Status'); functionSleep (ms) {varStart= NewDate ();  while (NewDate ()-Start<=ms) {}} Dobtn.onclick= function(e) {status.innerhtml= 'doing...please Wait ...'; Sleep ( the); //simulates a long-time computational process, 3sstatus.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 doing the status.innerhtml Setup, the GUI rendering thread needs to be executed, but the JavaScript engine thread is still executing, and the JavaScript engine thread is mutually exclusive to the GUI render thread. So the last show is done.

2) using the SetTimeout function

<ahref="#"ID= "DOBTN2">Do something timer</a><DivID= "Status2"></Div><Scripttype= "Text/javascript">      vardoBtn2=document.getElementById ('doBtn2'), Status2=document.getElementById ('Status2'); functionSleep2 (ms) {varStart= NewDate ();  while (NewDate ()-Start<=ms) {}} Dobtn2.onclick= function(e) {status2.innerhtml= 'doing...please Wait ...'; SetTimeout (function() {SLEEP2 ( the); status2.innerhtml= ' Done';           },  -);           return false; };</Script>

In "doing...please wait..." After adding a settimeout, delay execution, give the browser to render time, this time will show "doing...please wait..." , then executes the sleep function and finally shows "done."

Demo Download:

http://download.csdn.net/download/loneleaf1/7955393

Http://ejohn.org/blog/how-javascript-timers-work/How JavaScript Timers work
An analysis of Http://heroicyang.com/2012/08/28/javascript-event-loop/JavaScript event loop
Can http://www.2cto.com/kf/201204/129337.html JavaScript be multithreaded?
http://www.nowamagic.net/librarys/veda/detail/787 optimized JS script design to prevent the browser from suspended animation
http://www.ruanyifeng.com/blog/2013/10/event_loop.html What is event loop?

JavaScript timer (one)--single thread

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.