Javascript callback function

Source: Internet
Author: User

Many people confuse the concepts of callback and asynchronous.

1. Definition

CallbackWhat is it?
Check the callback _ (computer_programming) entries of the Wiki:

In computer programming, a callback is a reference to a piece of executable code that is passed as an argument to other code.

Jquery document how jquery works # callback_and_functio... entry:

A callback is a function that is passed as an argument to another function and is executed after its parent function has completed. the special thing about a callback is that functions that appear after the "parent" can execute before the callback executes.
Another important thing to know is how to properly pass the callback. This is where I have often forgotten the proper syntax.

Encyclopedia: callback Functions

A callback function is a function called by a function pointer. If you pass the pointer (address) of a function as a parameter to another function, when this pointer is used to call the function to which it points, we will say this is a callback function. The callback function is called by another party when a specific event or condition occurs instead of by the implementer of the function.EventOrCondition.

Therefore,Callback is essentially a design mode.And jquery (including other frameworks) follows this pattern.

In JavaScript, the callback function is defined as: function a is passed to another function B as a parameter (function reference), and function B executes function. Function A is called a callback function. If there is no name (function expression), it is called an anonymous callback function.

Therefore, callback is not necessarily used for Asynchronization. Callback is often used in synchronous (blocking) scenarios. For example, a callback function is required to be executed after certain operations.

2. Example

An example of using callback in synchronization (blocking) is to execute func2 after the func1 code is executed.

var func1=function(callback){    //do something.    (callback && typeof(callback) === "function") && callback();}func1(func2);    var func2=function(){}

Example of asynchronous callback:

$ (Document ). ready (callback); $. ajax ({URL: "test.html", Context: document. body }). done (function () {$ (this ). addclass ("done ");}). fail (function () {alert ("error ");}). always (function () {alert ("complete") ;});/** note that AJAX requests are indeed asynchronous, however, this request is a new thread request from the browser. When the Request status changes, if the 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. */
3. When will the callback be executed?

The callback function is generally last executed in a synchronous situation, but may not be executed in an asynchronous situation because the event is not triggered or the conditions are not met.

4. Usage of callback Functions
  • Resource loading: callback is executed after JS files are dynamically loaded, callback is executed after IFRAME is loaded, callback for Ajax operations, callback for image loading completion, Ajax, and so on.
  • DOM events and node. js events are based on callback mechanisms (node. js callbacks may cause multi-layer callback nesting issues ).
  • The latency of setTimeout is 0, which is often used. The setTimeout function is actually a callback.
  • Chained call: When a chained call is made, it is easy to implement chained call in the setter method (or in a method that does not return a value), while Getter) it is relatively difficult to implement chained call, because you need the iterator to return the data you need instead of the this pointer. If you want to implement the chained method, you can use the callback function to implement it.
  • SetTimeout and setinterval functions call to obtain their return values. Because both functions are asynchronous, that is, their call sequence and the main process of the program are relatively independent, there is no way to wait for their return values in the subject, when they are opened, the program will not stop and wait. Otherwise, the meaning of setTimeout and setinterval will be lost. Therefore, it is meaningless to use return, and only callback can be used. Callback notifies the proxy function of the result of timer execution for timely processing.
5. Passing callback Functions

As mentioned above, function references or function expressions must be passed as parameters.

Pai.get('myhtmlpage.html ', mycallback); // This is the correct example. get('myhtmlpage.html', mycallback ('foo', 'bar'); // This is an error. What about parameters? Pai.get('myhtmlpage.html ', function () {// use the function expression mycallback ('foo', 'bar') with parameters ');});

In addition, it is best to ensure that the callback exists and must be a function reference or function expression:

(callback && typeof(callback) === "function") && callback();

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.