JavaScript Asynchronous Programming-settimeout

Source: Internet
Author: User

JavaScript's execution engine is single-threaded and normally is a synchronous programming pattern, in which the program executes sequentially from top to bottom in the order of the Code. As long as one task takes a long time, the subsequent tasks must be queued, delaying the execution of the entire program. The common browser is unresponsive (suspended animation), often because a certain piece of JavaScript code is running for a long time (such as a dead loop), then any UI updates will be blocked during execution, and interface event processing will stop responding. Causes the entire page to be stuck in this place and other tasks cannot be performed.

Especially in the FOR Loop statement, if the processing logic of the For loop is complicated and the number of loops is too many, more than 1000 times, the execution of the JavaScript will block the browser from being handled with a noticeable state of suspended animation. The reason is that when the browser calls JavaScript, the main interface is stopped responding, because the CPU is given to JS execution, there is no time to process the interface message.

In order to solve the problem of the card, many people put forward the solution of asynchronous programming, which is also one of the ways of performance optimization, in the browser side, the long-time operation should be executed asynchronously, to avoid the browser to lose response. Now the Nodejs of the fire is asynchronous programming, such as routing, IO Operations, are asynchronous.

In the front-end page implementation, the most common asynchronous is the Ajax operation, request an AJAX without waiting for Ajax to return, you can continue to manipulate the page.

The other way through,,, and setTimeout setInterval so on image.onload postMessage,webwork asynchronous programming implementation.

There are also many libraries on the web that implement asynchronous programming such as:.,,, do.js step.js async.js flow.js do not elaborate, interested in Google to understand.

SetTimeOut

This is mainly about the way settimeout implements asynchronous programming.

Look at the code first, http://jsfiddle.net/jd_felix/mmrL66na/1/.

<! DOCTYPE html>varUpdatesync =function() {         for(vari = 0; i < 1000; i++) {            $(' #js_output '). text (i); }    }    varUpdateasync =function() {        vari = 0; functionUpdatelater () {$ (' #js_output '). Text (i++); if(I < 1000) {setTimeout (Updatelater,0);    }} updatelater (); }</script><body><button onclick= "Updatesync ()" > Sync Demo</button><button onclick= " Updateasync () "> Async demo</button><div id=" Js_output "></div></body>

Click Sync Demo: You'll feel the button pressed down and then see a final result of 99999, without the intermediate process, which is because the UI update is blocked while the Updatesync function is running, and the UI is updated only when it ends exiting.

Click Asynchronous Demo: You'll see a quick update of the process from 0 to 999 on the UI interface, which is the result of asynchronous execution. The function first declares a local variable i and nested function updatelater, and then calls the Updatelater, in this function first update the output node of the content of I, and then through settimeout let Updatelater function asynchronous execution. This is actually a recursive invocation. Any for loop can be transformed into a recursive invocation form.

Why use SetTimeout (fn,0), still can see the quick update?

This is because although his delay is set to 0, almost instantaneous trigger, but still be added to the execution queue, but this process, the rendering is finished, when he callback function execution, the output is already the updated value.

As a result, it is clear that asynchronous operations do not block the UI, and you can continue to perform other browser operations. Make UI operations smoother, but asynchronous programming can also be bad, as the code above, and setTimeout the asynchronous way that you use it, is much more time-consuming than synchronous execution in terms of overall code execution efficiency. At the same time, because it is asynchronous execution, interrupts the execution order of the original code, resulting in nested function calls, destroying the original simple logic, so that the code is difficult to read.

It is easy to implement in synchronous programming when judging whether the execution is complete, and the code is written behind the For loop. and asynchronous words, you need to make some judgments.

Or the above example, how do callbacks execute after the loop is finished? Can be Jquery used $.when , and $.Deferred methods, of course, you can write the callback function, but it does not look so elegant.

varwait =function(){        varDTD = $.        Deferred (); vari = 0; functionUpdatelater () {$ (' #js_output '). Text (i++); if(I < 1000) {setTimeout (Updatelater,0); }            if(i = = 1000) {dtd.resolve ();//changing the execution state of a deferred object}} updatelater (); returnDtd.promise ();//returns the Promise Object    }    varUpdateasyncback =function() {$.when (Wait ()). Done (function() {alert (' done! '); })    }

In the original, see: http://faso.me/notes/20131123/javascript-synchronous-settimeout/

JavaScript Asynchronous Programming-settimeout

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.