Understanding of JavaScript Callback functions

Source: Internet
Author: User

In JavaScript, the callback function is specifically defined as: function A is passed as a parameter (function reference) to another function B, and this function B executes function A. Let's just say that function A is called a callback function. If there is no Name (function expression), it is called an anonymous callback function.

Callback are not necessarily used for asynchrony, and callbacks are often used in scenarios where general synchronization (blocking) is required, such as executing a callback function after certain operations have been performed.

Callbacks and Synchronizations

Example of using callbacks in synchronous (blocking)

var func1=function(callback) {    //dosomething.    typeof (callback) = = = "function") &&//fun1 execution after execution fun2var func2=  function//fun2 definition }
Callbacks and Async

Examples of asynchronous callbacks:

// The Ready function registers the callback function $ (document). Ready (callback);

// Ajax Async $.ajax ({  "test.html",  Context:document.body}). Done (function() {   $ (  this). AddClass ("Done");}). Fail (function() {alert ("error");}). Always (function() {alert (' complete ');}); /* * Note that the AJAX request is indeed asynchronous, but the request is made by a new thread request from the browser, and when the state of the request is changed, if the callback was previously set, the asynchronous thread will generate a state change event to be placed in the processing queue of the JavaScript engine for processing. See: Http://www.phpv.net/html/1700.html* /
When is the callback executed?

Callback functions, which are typically executed in a synchronous context, 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: Execute callback after dynamically loading JS file, execute callback after loading IFRAME, Ajax operation Callback, image loading complete execution callback, Ajax and so on.
    • Events: DOM events and node. JS events are based on callback mechanisms (node. JS callbacks may have multiple layers of callback nesting issues).
    • SetTimeout delay Time is 0, this hack is often used, settimeout call function is actually a callback embodiment
    • Chained invocation: When chaining calls, it is easy to implement chained calls in the evaluator (setter) method (or in a method that does not have a return value in itself), and the accessor (getter) is relatively bad for chaining calls because you need the accessor 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 the "not very understanding"
    • The function Call of SetTimeout, SetInterval, gets its return value. Since all two functions are asynchronous, that is, their call timing and the program's mainstream process is relatively independent, so there is no way to wait for their return value in the body, they are open when the program will not stop waiting, otherwise it will lose the meaning of settimeout and setinterval, so There is no point in using return, only callback. The meaning of "callback" is to notify the agent function of the result of the timer execution to deal with it in time.

delivery of callback functions

To pass a function reference or function expression as a parameter.

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

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 ();

The process after the "Notification main thread" (callback) is executed (the function is completed).

JS is how to implement callbacks? Through Message Queuing and event loops.

Reference

http://mao.li/javascript/javascript-callback-function/

The author starof, because the knowledge itself in the change, the author is also constantly learning and growth, the content of the article is not updated regularly, in order to avoid misleading readers, convenient tracing, please reprint annotated source: http://www.cnblogs.com/starof/p/6888178. HTML has a problem welcome to discuss with me, common progress.

Understanding of JavaScript Callback functions

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.