Asynchronous execution of setTimeout and JS Engine

Source: Internet
Author: User

See an article from time to timeArticleTimedchunk is used to improve user experience. timedchunk can greatly improve user experience, however, this article does not introduce the underlying reasons for this performance optimization method, and the "Large Array" example may cause many people to misunderstand it. setTimeout is more useful than that. Here, timedchunk is a method called for using setTimeout for hack for a single JS engine process in Nicholas C. zakas. John resig has long provided an explanation of the setTimeout working mechanism, which describes the processing of setTimeout by the single-process mode JS engine, the JS engine of all browsers is not analyzed in detail. After all, not all JS engines are single processes. However, this article is already quite authoritative.

How does timedchunk optimize the experience based on setTimeout? Why can't setTimeout only partially optimize the experience, but not the performance? When do I need to use setTimeout? How to use setTimeout for hack on IE? Why does the ie js engine need to use hack for the ecmascript mode? This article will answer these questions one by one.

First, it is clear that most JS engines are single-process interpreters, or in a Web page, JS is executed by a single process, that is, the browser cannot execute JS while rendering the page. Rendering here is a "rendering" operation that scales up the granularity. No matter how fast the browser renders the page, it will take a certain amount of time, in this time, the browser cannot do anything else, just like in the minimum time slice unit of the CPU, the CPU can only perform operations on one task. Although the time slice length of browser scheduling rendering and JS threads is much larger than the minimum time slice of CPU. In addition, the browser calls the functions in the stack sequentially.

As shown in the figure, the JS engine filters out JSCodeSplit the code segment and render the page after JS modifies the DOM node,
This is reasonable to let the page see the result of JS operations on Dom. Of course, we usually want the browser to execute it according to such fixed logic,
Most browsers do the same in most cases, but sometimes there are deviations.
For example, when operations on several DOM nodes in Javascript change to one another, and the total time required for operations on each Dom node is less than that of the browser to process a single process
The minimum time slice, the performance of different browsers is inconsistent, but usually when the browser memory is abundant,
The browser splits several consecutive Dom operations according to the minimum part time of the browser, that is, the time of the two or three dom operations and
It is larger than the minimum time slice used by the browser to process a single process. This is a page rendered by the browser only after two or three dom operations. However, when the browser memory is tight
Some browsers merge the DOM operation sets of the single-process time slice with a time interval less than the browser into one browser operation,
As a stack scheduling, the browser will wait for these adjacent Dom operations to render the page once,

Of course, different browsers have different sizes for the minimum sharding of a single process, and different browsers are also considering the JS engine speed,
It will merge several Dom operations into one stack scheduling. Most browsers are very careful about the hack of the JS engine,
Although there will be poor user experience due to untimely rendering, at least the CPU-side render page can be burned slowly,
However, ie has made some clever hack with serious bugs. For example, in IE, JS operations on DOM nodes without the haslayout attribute will not trigger render,
For example, if dom does not have the display = block attribute, changing its attribute will not trigger Rander,
Therefore, many people often encounter some strange things when writing JavaScript code, complaining that they have changed the attributes of DOM nodes in JavaScript,
The change was successful, but the result of the change was not displayed in the browser. To improve this situation, there is only one method: asynchronous call.

most of the asynchronous concepts we generally understand come from Ajax, that is, when a page initiates a request to the backend, it should not wait for the returned results.
instead, it should continue to execute, if a callback is returned, the execution time of the callback function is not fixed.
it depends on the back-end response. During the rendering of a single process in the browser, the adjacent Dom operations are used as Asynchronous events.
in this way, the DOM operations will be skipped and the DOM operations will be executed at the right time,
at this time, the executed Dom operation and the original logic are no longer in the single process time of a browser, that is, they do not belong to a stack call.
if each Dom operation is used as an asynchronous event, all Dom operations are used as separate stack calls,
in this way, the browser inserts a rendering operation after these independent parts, so that each Dom operation is rendered to the page.
. SetTimeout can be used to put a function into an independent stack as an asynchronous call.
although the delay of setTimeout is 0, it is also used as an asynchronous call, after each asynchronous call, the render page is displayed.
This is a better experience than the render after batch Dom operations in the browser. You can see this example.

<Br/> <! Doctype HTML> <br/> <HTML dir = "LTR" lang = "ZH-CN"> <br/> <pead> <br/> <meta charset = "UTF-8" /> <br/> <meta http-equiv = "X-UA-compatible" content = "Ie = edge"> <br/> </pead> <br/> <body> <br/> <p> Example 1 </p> <br/> <button id = "clickme1"> continuous Dom operations without setTimeout </button> <br/> <button id = "clickme2"> defines a continuous Dom operation for setTimeout </button> </P> <p> <Div style = "width: 1px; Background: red; overflow: hidden; Height: 22px; "id =" JD "> progress </Div> <br/> <Div id = 'alink 'style = "height: 200px; overflow: auto; "> logs here </div> </P> <p> <SCRIPT type =" text/JavaScript "src =" http://cn.yimg.com/ I /yui/3.0.0b1/build/yui/yui-min.js "> </SCRIPT> <br/> <script> <br/> <! -- <Br/> Yui (). use ('node', function (y) {</P> <p> // define the level of brute force <br/> var rang = 300; </P> <p> var handlepercent = function (k) {<br/> var W = math. floor (K/rang * 100); <br/> Y. node. get ('# JD '). setstyle ('width', W + 'px'); <br/>}; </P> <p> Y. on ('click', function (e) {<br/> Y. node. get ('# alink '). set ('innerhtml ', ''); <br/> var K = 0; <br/> var T = new date (); <br/> for (VAR I = 0; I <rang; I ++) {<br/> Y. node. get ('# alink '). se T ('innerhtml ', Y. node. get ("# alink "). get ('nerhtml ') +' <br/> '+ (K ++); <br/> handlepercent (k); <br/> Y. node. get ('# JD '). set ("innerhtml", (Number (new date ()-number (t); <br/>}</P> <p> }, '# clickme1'); <br/> Y. on ('click', function (e) {<br/> Y. node. get ('# alink '). set ('innerhtml ', ''); <br/> var K = 0; <br/> var T = new date (); </P> <p> var Foo = function () {<br/> Y. node. get ('# alink '). set ('innerhtml ', Y. node. g Et ("# alink "). get ('nerhtml ') +' <br/> '+ (K ++); <br/> handlepercent (k); <br/> Y. node. get ('# JD '). set ("innerhtml", (Number (new date ()-number (t); <br/> If (K! = Rang) setTimeout (arguments. callee, 0); <br/>}; <br/> setTimeout (Foo, 0); </P> <p >}, '# clickme2 '); </P> <p> }); </P> <p> // --> <br/> </SCRIPT> <br/> </body> <br/> </ptml> <br/>

Run code

 
<Input type = "text" value = "A" name = "input" onkeydown = "alert (this. value) "/> <input type =" text "value =" A "name =" input "onkeydown =" Var me = This; setTimeout (function () {alert (Me. value)}, 0) "/>

Let's try to add a new string after text field.

The second example illustrates the asynchronous call of setTimeout and browser events. Although the delay of setTimeout is 0, it is still put into another stack call and called only after the event ends.

After understanding this process, we will understand why using setTimeout can only improve the experience but not the performance. setTimeout will have many more render operations, of course, it will be slow, in the example I gave, it is obvious that the time consumed for asynchronous page rendering is nearly doubled, but it is worth comparing with the improvement of user experience. Therefore, when the JS logic contains a large number of loops causing continuous Dom node modifications, setTimeout should be used to improve the experience. If the prompt render page is not found during ie debugging, you can use setTimeout to hack for the preceding reasons. IE's hack for consecutive Dom operations is probably in performance consideration. Windows's performance was not flattering, and it would be slower to run ie again, various Network tests are enough to prove that IE's Js engine is the worst. Therefore, it would be strange for IE to develop CSS expressions and haslayout geeks for performance hack. Looking back at the analysis of the age, the so-called 25 ms is a guess of the minimum time slice for browser single process scheduling. This 25 ms should be related to the number of consecutive Dom operations, therefore, this prediction value is of little significance. If you wrap every Dom operation in setTimeout, setting delay to 0 is enough.

Some useful links

SetTimeout and setinterval

SetTimeout

SetTimeout calls a function with a returned value

Recognize setTimeout with a delay of 0

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.