Javascript timer (1) -- single thread

Source: Internet
Author: User
Tags sleep function

Javascript timer (1) -- single thread
1. the JavaScript engine is single-threaded and can be seen from the following code. The first code in setTimeout is an endless loop, the following two timers have no chance to execute. <Script type = "text/javascript"> setTimeout (function () {while (true) {}}, 100); setTimeout (function () {alert ('Hello! SetTimeout ') ;}, 200); setInterval (function () {alert ('Hello! SetInterval ') ;}, 200); </script> the kernel of the browser is multi-threaded. They work with each other under the kernel control to maintain synchronization. A browser must implement at least three resident threads: javascript Engine thread, GUI rendering thread, and browser event triggering thread. 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. Time t1: GUI rendering thread browser event trigger thread: during the time period t1, the user clicks a mouse key and then clicks it to be captured by the browser event trigger thread to form a mouse click 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. Timed trigger thread: the browser model timing counter is not counted by the JavaScript engine, because the JavaScript engine is single-threaded and cannot be counted if it is in the blocked thread state, it depends on external timing and triggers timing. Therefore, scheduled events in the queue are asynchronous events. In 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. Ajax asynchronous request: the browser opens an http thread request. When the Request status changes, if callback has been set previously, this asynchronous thread generates a state change event, which is placed in the processing queue of the JavaScript engine to be processed. 2. The execution sequence of the task is different, and the display result is also different. 1) A code instance found online without the setTimeout function is used for demonstration. Copy the Code <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> copy the code and 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) use the setTimeout Function to copy the Code <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> copy the code 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. Copy the Code <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>

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.