Javascript asynchronous programming

Source: Internet
Author: User

It is like waiting in the queue. The people in front of the queue are busy and suddenly go to the toilet. the people behind the queue are blocked here. Therefore, we need to let the people in front of the queue die and let the people behind follow up ...... AJAX is the concept. The request continues, but we can do other things.

The setTimeout Function of BOM is implemented in javascript, but DOM operations also provide a series of implementations. For example, XMLHttpRequest object and script tag onreadystatechange callback, image onload and onerror callback, iframe onload, DOM element Event Callback, and HTML5 cross-domain message transmission postMessage, loading of QuickTime and flash objects ......

The zero-second delay of setTimeout was widely publicized in China in the past few years. However, setTimeout is the slowest of all latencies and takes at least 10 milliseconds. If setTimeout is used to develop special effects, this effect runs slowly. The following is a performance test:
<! Doctype html> <ptml lang = "en"> <pead> <title> Async performance test </title> <meta charset = "gb2312"> <style> pre {background-color: # eeeeee; padding: 20px;} div. test {margin: 20px; padding: 10px; border: solid black 1px ;}</style> </pead> <body> setTimeout (slow, takes about 10 sec) <pre class = "source"> function async (callback) {setTimeout (callback, 0 );} </pre> <p> <input type = "button" value = "run" onclick = "runtest (this. parentNode. parentNode) "> </p> img. onerror (data: uri) <pre class = "source"> function async (callback) {var img = new Image; img. addEventListener ('error', callback, false); img. src = 'data:, foo';} </pre> <p> <input type = "button" value = "run" onclick = "runtest (this. parentNode. parentNode) "> </p> script. onreadystatechange <pre class = "source"> function async (callback) {var script = document. createElement ("script"); script. type = "text/javascript"; script. src = "javascript:"; script. onreadystatechange = function () {document. body. removeChild (script); callback ();} document. body. appendChild (script) ;}</pre> <p> <input type = "button" value = "run" onclick = "runtest (this. parentNode. parentNode) "> </p> script. onload (data: uri) <pre class = "source"> function async (callback) {var script = document. createElement ('script'); script. onload = function () {document. body. removeChild (script); callback ();} script. src = 'data: text/javascript, '; document. body. appendChild (script) ;}</pre> <p> <input type = "button" value = "run" onclick = "runtest (this. parentNode. parentNode) "> </p> xhr. onreadystatechange (data: text/plain, foo) <pre class = "source"> function async (callback) {var xhr = new XMLHttpRequest; xhr. open ('get', 'Data: text/plain, foo', true); xhr. onreadystatechange = function () {xhr. onreadystatechange = null; callback () ;}; xhr. send (null) ;}</pre> <p> <input type = "button" value = "run" onclick = "runtest (this. parentNode. parentNode) "> </p> self. postMessage <pre class = "source"> function async (callback) {var n = ++ async. count; window. addEventListener ('message', function (e) {if (e. data = n) {window. removeEventListener ('message', arguments. callee, false); callback () ;}, false); window. postMessage (n, location. protocol + "//" + location. host);} async. count = 0; </pre> <p> <input type = "button" value = "run" onclick = "runtest (this. parentNode. parentNode) "> </p> </body> </ptml>
[Ctrl + A select all Note: If you need to introduce external Js, You need to refresh it to execute]

Chromium Safari Firefox Opera 10.10 Opera 10.50
SetTimeout 4.32 ms 10.201 ms 10.302 ms 10.38 ms 9.876 ms
Img. onerror 0.199 ms 0.678 ms 0.201 ms 0.058 ms 0.575 ms
Script. onreadystatechange Fail Fail Fail Fail Fail
Script. onload 0.414 ms 0.138 ms 0.414 ms Fail Fail
Xhr. onreadystatechange Fail 0.622 ms Fail 0.078 ms 0.079 ms
Self. postMessage 0.096 ms 0.123 ms 0.112 ms 0.049 ms 0.094 ms

To handle this asynchronous call, Mochikit borrowed the Deferred class from the Python Twisted framework and used it to process AJAX callback. There are two types of AJAX callbacks: callback upon successful loading and callback upon request failure. XDomainRequest of IE8 has these two types of callbacks, the script and image of the standard browser also have these two types of callbacks, called onload and onerror respectively. The Deferred instance of Mochikit has a built-in array, which is included in each callback and executed in sequence. Mochikit, a great heritage, was later carried forward by dojo. As for how to use it, google it.

The following is my framework's application. I have integrated it into my framework:
Copy codeThe Code is as follows:
<! Doctype html>
<Html>
<Head>
<Title> Asynchronous Operation example by situ zhengmei </title>
<Meta charset = "UTF-8"/>
<Meta content = "IE = 8" http-equiv = "X-UA-Compatible"/>
<Meta name = "keywords" content = "Asynchronous Operation example by situ zhengmei"/>
<Meta name = "description" content = "Asynchronous Operation example by situ zhengmei"/>
<% = Javascript_include_tag "dom. js" %>
<% = Javascript_tag "window. _ token = '# {form_authenticity_token}'" if ActionController: Base. allow_forgery_protection %>
<Script type = "text/javascript" charset = "UTF-8">
Dom. ready (function (){
Dom. require ("ajax ");
Dom. ajax ({method: "post ",
Async: true,
DataType: "text ",
Data: {authenticity_token: window. _ token}
}). Next (function (){
Alert ()
});
Dom. jsonp ({url: "http://del.icio.us/feeds/json/fans/stomita"}). next (function (json ){
Alert (json)
}). Error (function (e ){
Alert (e)
});
});
</Script>
</Head>
<Body>
</Body>
</Html>

Background:
Copy codeThe Code is as follows:
Class HomeController <ApplicationController
Def index
If request. xhr?
Name = params [: name]
Puts "-------------"
Render: text => "<p> The time is <B>" + DateTime. now. to_s + "</B> </p>"
End
End
End

The Japanese blog mentioned an example of capturing asynchronous errors:
Copy codeThe Code is as follows:
Function throwError (){
Throw new Error ('error ');
}
Try {
SetTimeout (throwError, 3000 );
} Catch (e ){
Alert (e );
}

It seems that try... catch cannot catch errors in this form. window. onerror is acceptable, but it seems that only IE and FF are supported. If Deferred is used for processing, it's easy!
Copy codeThe Code is as follows:
Dom. Deferred. next (function (){
Throw new Error ("Error ")
}). Wait (1). error (function (e ){
Alert (e instanceof Error)
});

Queue processing. Because asynchronous mode is used, the page presentation will not be blocked.
Copy codeThe Code is as follows:
<! Doctype html>
<Html>
<Head>
<Title> Asynchronous Operation example by situ zhengmei </title>
<Meta charset = "UTF-8"/>
<Meta content = "IE = 8" http-equiv = "X-UA-Compatible"/>
<Meta name = "keywords" content = "Asynchronous Operation example by situ zhengmei"/>
<Meta name = "description" content = "Asynchronous Operation example by situ zhengmei"/>
<% = Javascript_include_tag "dom. js" %>
<Script type = "text/javascript" charset = "UTF-8">
Dom. require ("deferred ");
Dom. require ("query ");
Dom. ready (function (){
Var a = dom ("# aaa") [0];
Dom. Deferred. loop (10, function (I ){
A. innerHTML + = I + "<br/>"
});
Dom. Deferred. loop (10, function (I ){
A. innerHTML + = String. fromCharCode (I + 97) + "<br/>"
});
Dom. Deferred. loop (10, function (I ){
A. innerHTML + = "situ zhengmei" + I + "<br/>"
});
});
/* Result
0
A
Situ zhengmei 0
1

Situ zhengmei 1
2
C
Situ zhengmei 2
3
D
Situ zhengmei 3
4
E
Situ zhengmei 4
5
F
Situ zhengmei 5
6
G
Situ zhengmei 6
7
H
Situ zhengmei 7
8
I
Situ zhengmei 8
9
J
Situ zhengmei 9
*/
</Script>
</Head>
<Body>
<Div id = "aaa"> </div>
</Body>
</Html>

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.