Tell you what a JavaScript callback function _ Basics

Source: Internet
Author: User
Tags anonymous setinterval

  function is also an object

To figure out the callback function, first clearly understand the rules of the function. In JavaScript, a function is rather strange, but it is indeed an object. Rather, a function is an object created with a function () constructor. The function object contains a string containing the JavaScript code for the functions. If you turn from C or Java, it may seem strange, how can the code be a string? But for JavaScript, this is normal. The difference between the data and the code is very vague.

You can do this by creating the function
var fn = new function ("Arg1", "arg2", "return arg1 * ARG2;");

One advantage of doing this is that you can pass code to other functions, or you can pass a regular variable or object (because the code is literally just an object).

  Pass function as callback

It's easy to pass a function as a parameter.

function fn (arg1, arg2, callback) {
 var num = Math.ceil (Math.random () * (ARG1-ARG2) + arg2);
 Callback (NUM); Passing results

fn (num) {
 console.log ("Callback called!    NUM: "+ num); 
}"; Random number with a result of 10 and 20 

It might seem like a bit of a hassle, even a little silly, and why did you return the results abnormally? But when you have to use the callback function, you may not think so!

Get out of the way

The traditional function enters data as a parameter and returns a value using the return statement. Theoretically, there is a return statement at the end of the function, structurally: an input point and an output point. It is easier to understand that a function is essentially a mapping of the implementation process between input and output.

However, when the implementation of the function is very long, do you choose to wait for the function to complete processing, or use the callback function for asynchronous processing? In this case, it becomes critical to use a callback function, such as an AJAX request. If you use a callback function for processing, the code can continue to perform other tasks without having to wait. In actual development, asynchronous calls are often used in JavaScript, and are even strongly recommended here!

Here's a more comprehensive example of using AJAX to load an XML file and using the call () function to invoke the callback function in the context of the request object (requested object).

function fn (URL, callback) {
 var HttpRequest; Create xhr
 HttpRequest = window. XMLHttpRequest? New XMLHttpRequest ()://For IE for functional detection
window. ActiveXObject? New ActiveXObject ("Microsoft.XMLHTTP"): undefined;
 Httprequest.onreadystatechange = function () {
  if (httprequest.readystate = = 4 && httprequest.status = 200 {//State judgment (httprequest.responsexml); 
 }; ("get", url);
 Httprequest.send ();

FN ("Text.xml", function () {//Call functions
 console.log (this); After this statement is output

Console.log ("This'll run before the above callback."); This statement first outputs 

We request asynchronous processing, which means that when we start the request, we tell them to call our functions when they are done. In practice, the onReadyStateChange event handler also has to consider the failure of the request, where we assume that the XML file exists and can be successfully loaded by the browser. In this example, the asynchronous function is assigned to the onReadyStateChange event, so it is not executed immediately.

Finally, the second Console.log statement executes first because the callback function does not execute until the request completes.

The above example is not easy to understand, so look at the following example:

function foo () {
 var a = ten;
 return function () {
  a *= 2;
  return A;  
var f = foo ();
f (); return 20.

function is called externally, you can still access variable A. This is because the scopes in JavaScript are lexical in nature. Functions run in the scope that defines them (the scope within Foo in the example above) rather than the scope in which this function is run. As long as f is defined in Foo, it can access all the variables defined in Foo, even if the execution of Foo is finished. Because its scope is saved, it is only the returned function that can access the saved scope. Returning an inline anonymous function is the most common means of creating closures.

What's the callback?

Look at Wikipedia's Callback_ (computer_programming) Entry:

In computer programming, a callback are a reference to a piece of executable code this is passed as a argument to other CO De.

jquery documentation how jquery works#callback_and_functio ... Entry:

A callback is a function this is passed as a argument to another function and are executed after its parent function has C ompleted. The special thing about a callback is this functions that appear after the "parent" can execute before the callback Execut Es. Another important thing to know are how-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 to another function as an argument, when the pointer is used to call the function it points to, we say this is a callback function. A callback function is not invoked directly by the implementing party of the function, but is invoked by another party when a particular event or condition occurs, and is used to respond to the event or condition.

As a result, callbacks are essentially a design pattern, and the design principles of jquery (including other frameworks) follow this pattern.

In JavaScript, the callback function is specifically defined as: function A is passed to another function B as an argument (a function reference), and this function B executes function A. Let's just say 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 in asynchronous, general synchronization (blocking) scenarios are often used in the callback, such as the requirement to perform some operations after the callback function.

An example of using callbacks in a synchronization (blocking) to execute FUNC2 after func1 code execution completes.

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

Func1 (FUNC2);
  var func2=function () {

Example of an asynchronous callback:

$ (document). Ready (callback);

$.ajax ({
 URL: "test.html",
}). Done (the function () { 
 $ (this). AddClass ("Done ");
}). Fail (function () {alert (' error ');
}). Always (function () {alert ("complete"); 
Note that the AJAX request is indeed asynchronous, but this request is a new thread request from the browser, and when the requested state changes, if the callback was previously set, the asynchronous thread is placed in the processing queue of the JavaScript engine waiting to be processed. */

When will the callback be executed?

Callback functions, which are generally executed in the context of synchronization, may not be executed in an asynchronous context because the event is not triggered or the condition is not satisfied.

Use of callback functions

Resource loading: Dynamically loading JS files after the callback, loading the IFRAME to perform the callback, Ajax operation callback, picture loading complete execution callback, Ajax and so on.
DOM events and Node.js events are based on a callback mechanism (a Node.js callback may have problems with multi-tier callback nesting).

SetTimeout delay Time is 0, this hack is often used, settimeout called function is actually a callback embodiment

Chained call: When chained call, it is easy to implement chained calls in the assignment (setter) method (or in a method that does not have a return value in itself), and the accessor (getter) is relatively difficult to implement chained calls, because you need to return the data you need instead of the this pointer. If you want to implement a chained method, you can use a callback function to implement a settimeout, setinterval function call to get its return value. Since two functions are asynchronous, that is: their call time sequence and the main process of the program is relatively independent, so there is no way to wait for their return value in the main body, they are opened when the program will not stop to wait, otherwise it will lose the meaning of settimeout and setinterval, So using return has no meaning, only use callback. The significance of the callback is to notify the agent function of the result of the timer execution to be processed in time.

Passing of callback functions

It says, to pass a function reference or a function expression as a parameter.

$.get (' myhtmlpage.html ', mycallback);//This is the right
$.get (' myhtmlpage.html ', Mycallback (' foo ', ' Bar '));/This is wrong, then take the parameters?
$.get (' myhtmlpage.html ', function () {///with parameter expression
mycallback (' foo ', ' Bar ');

In addition, it is best to guarantee that a callback exists and must be a function reference or a function expression:
(Callback && typeof (callback) = = "function") && callback ();

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: 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.