JavaScript Asynchronous Programming

Source: Internet
Author: User


1. What is asynchronous (asynchronous) programming?

In contrast to synchronization (synchronous), Async is the latter task that does not need to wait for the previous task to end and executes the callback function at the end of the previous task.

The most common asynchronous programming has settimeout functions, Ajax requests, and so on.

Such as:

for (var i = 1; I <= 3; i++) {
SetTimeout (function () {
Console.log ("#", I);
}, 0);
Console.log ("*", I);
};

The result of the output is: * * * #4 #4 #4

The knowledge points involved:asynchronous, closure, scope

SetTimeout is a registration event that is not invoked until the main program is finished running.

Just like binding a click event for a Div, the event is not triggered until you click it.

This is an example of a common asynchronous programming.


2. Methods of asynchronous Programming

Ⅰ, callback function

Suppose there is a F1 (); F2 (); Two functions, where F2 () is waiting for the execution result of F1 ().

function F1 (F2) {
SetTimeout (function () {
F2 ();
}, 1000);
}

Code Execution Order: F1 (F2);

Pros: F1 does not clog the program running, equivalent to executing the main logic of the program, delaying the execution of time-consuming operations
Cons: not conducive to reading and maintenance of code, highly coupled between sections (coupling), and only one callback function can be specified per task

Ⅱ, event monitoring

F1.on (' Done ', f2);//jquery notation, when F1 happens, execute F2

Function F1 () {
SetTimeout (function () {
F1.trigger (' done ');//When execution is complete, the Do event is immediately triggered
}, 1000);
}

Pros: Multiple events can be bound, each event can specify multiple callback functions, and can be "decoupled" (decoupling), to facilitate the implementation of modular
Cons: The entire program becomes event-driven and the running process becomes unclear


Ⅲ, publish/Subscribe

Jquery.subscribe ("Done", F2);//f2 subscribe to jquery for "done" signals

Function F1 () {
SetTimeout (function () {
Jquery.publish ("Done"); after//f1 execution completes, the "Do" signal is released to jquery, triggering the execution of F2
}, 1000);
}


Ⅳ, promises objects

The idea is that each asynchronous task returns an promise object that has a then method that allows you to specify a callback function. For example, F1 's callback function, F2, can be written as:

F1 (). then (F2);

The F1 is rewritten as follows:

Function F1 () {
var DFD = $. Deferred ();
SetTimeout (function () {
Dfd.resolve ();
}, 500);
return dfd.promise;
}

Pros: The callback function becomes a chained notation, the process of the program can be seen clearly, you can specify multiple callback functions, such as:

F1 (). Then (F2). then (F3);
F1 (). Then (F2). Fail (F3);

Cons: Writing and understanding are relatively difficult

Several concepts are attached:

first, the incident

An event is a specific interaction moment that occurs in a document or browser window.

ii. Registration of events

Registration events are categorized as attribute registration and method registration.

Property Registration: 1. Attribute assignment embedded in the DOM structure

HTML: <button onclick= "SayHello ()" > Click </button>

Js:function SayHello () {
Console.log (' Hello ')
}

2. Specifying the attribute assignment of an element object via JS

Document.body.onclick = function (e) {
Alert ("Register a Click event for Body");
};

Method Registration: 1. Register with the AddEventListener () method

Note: In JS, window, document, HtmlElement and other objects can register event handlers through the AddEventListener () method.

Syntax: Eventtarget.addeventlistener (EventName, EventHandler, |usecapture)

Parameters:

①eventname {string}: The name of the event to register is not case-sensitive. This name does not need to be prefixed with "on" Like registering event properties. such as registering a mouse click event, write as Click.

②eventhandler {function | object}: Functions or Function objects. The function to execute when the event is triggered, and when the same event is registered multiple times using a function object, register it again.

③usecapture {Boolean} optional: is in the capture phase and defaults to false.

Multiple registrations: the AddEventListener () method can register multiple times for the same event of the same object. When this event occurs, the registered processing event program is executed in the order of registration.

Attention:

This method is not supported for IE before ①IE9, and can be replaced with attachevent ().

② If you use the same event handler object to register multiple times on the same event, only one registration is counted.

Cases:

Document.body.addEventListener (' click ', Function (e) {
Console.log (' Be clicked on One ');
});

Document.body.addEventListener (' click ', Function (e) {
Console.log (' Be clicked on Two ');
});

Document.body.click (); Output: Clicked one was clicked on two

2. Register through the Attachevent () method

Description: The version of IE prior to IE9 can register events by this method.

Syntax: Eventtarget.attachevent (EventName, EventHandler)

①eventname {string}: The name of the event to register is case-sensitive. The name here is the same as the event property, starting with "on" followed by the event name. such as: OnClick, onload.

②eventhandler {function | object}: Functions or Function objects. The function to execute when the event is triggered, and can be registered multiple times (The AddEventListener () method is only registered once) when the same event is registered multiple times with the function object.

Multiple registrations: the Attachevent () method can register multiple times for the same event of the same object. When this event is triggered, it is also executed sequentially.

Cases:

function Sayhellow () {
Console.log (' Hello ');
}
Document.body.attachEvent (' onclick ', sayhellow);
Document.body.attachEvent (' onclick ', sayhellow); Sayhellow registering the same event for the second time
Document.body.click (); Output 2 times sayhellow function: Hello Hello

Ii. Cancellation Events

JS, you can call RemoveEventListener () [Logoff AddEventListener ()] and detachevent () [Logoff attachevent ()] to unregister the handler for an event specified by an element, You can also assign a value of NULL to the event property to unregister all bindings for this event.

1.removeEventListener (eventName, function Object)

Description: Unregisters an event handler registered through AddEventListener ().

Syntax: Eventtarget.removeeventlistener (EventName, Eventhandlerobj)

Parameters:

①eventname {string}: The event name to unregister is not case-sensitive. This name does not need to be prefixed with "on" Like registering event properties. such as registering a mouse click event, write as Click.

②eventhandlerobj {Function Object}: Passing in a function body is not effective.

Cases:

SayHello function to unregister body Click event
Document.body.removeEventListener (' click ', SayHello);

2.detachEvent (eventName, function Object)

Description: Unregisters an event handler registered through Attachevent ().

Syntax: Eventtarget.detachevent (EventName, Eventhandlerobj)

Parameters:

①eventname {string}: The event name to unregister is case-sensitive. The name here is the same as the event property, starting with "on" followed by the event name. such as: OnClick, onload.

②eventhandlerobj {Function Object}:: Functions object. Passing in a function body is not effective.


Cases:

SayHello function to unregister body Click event
Document.body.detachEvent (' onclick ', SayHello);

3. Canceling an Event

Assigning a value of NULL to an object's event property cancels all registered processing events for this event.

Cases:

The OnClick property is assigned a value of NULL, which is equivalent to unregistering the onclick event
Document.body.onclick=null;


Reference Link: http://www.ruanyifeng.com/blog/2012/12/asynchronous%EF%BC%BFjavascript.html
Http://www.qdfuns.com/notes/17398/e8a1ce8f863e8b5abb530069b388a158/page/.html




JavaScript Asynchronous Programming

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.