Pass the function as a parameter into another function. This function is called a callback function
It is often encountered in this situation that the A and B layers of a project are completed by different personnel in collaboration. The A layer is responsible for the function funA, and the B layer is responsible for funcB. When B layer wants to use the data of a certain module, he told the A layer staff that I need you to provide data that meets certain needs, and you provide me with an interface.
The staff at Level A said: I will provide you with data, and how to display and process it is B's business.
Of course, layer B cannot provide a data interface for every requirement. B provides A with an interface to pass. B obtains the data, and then B writes the function to display it.
That is, you need to work with others and others provide data, and you don't need to focus on how others get or build data. You just need to operate on the data you get. You need to use a callback function at this time
Therefore, callbacks are essentially a design pattern, and the design principles of jQuery (including other frameworks) follow this pattern.
An example of using callbacks in synchronization (blocking) is to execute func2 after the func1 code is executed.
The code copy is as follows:
var func1=function(callback){
//do something.
(callback && typeof(callback) === "function") && callback();
}
func1(func2);
var func2=function(){
}
Example of asynchronous callbacks:
The code copy is as follows:
$(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 the ajax request is indeed asynchronous, but this request is requested by the browser. When the status of the request is changed, if a callback has been set before, the asynchronous thread will generate a state change event and put it in the processing queue of the JavaScript engine to wait for processing. See: http://www.phpv.net/html/1700.html
When will the callback be executed
Callback functions are usually executed last 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.
Use cases of callback functions
Resource loading: Execute callback after dynamic loading of js files, execute callback after loading iframe, execute callback after loading ajax operation callback, execute callback after image loading, AJAX, etc.
DOM events and Node.js events are based on callback mechanism (Node.js callbacks may have multi-layer callback nesting problems).
The delay time of setTimeout is 0. This hack is often used. The function called by setTimeout is actually a callback embodiment
Chain call: When chain call, it is easy to implement chain call in the evaluator (setter) method (or in methods that do not return values), but the value getter is relatively difficult to implement chain call, because you need the value getter to return the data you need instead of this pointer. If you want to implement chain method, you can use a callback function to implement it.
The function calls of setTimeout and setInterval get their return value. Since both functions are asynchronous, that is, their call timing and the main process of the program are relatively independent, there is no way to wait for their return value in the body, and the program will not stop and wait when they are opened, otherwise the meaning of setTimeout and setInterval will be lost. Therefore, it is meaningless to use return, so callback can only be used. The meaning of callback is to notify the proxy function of the timer execution results for timely processing.
I should have some information collected online and I should understand it. I will sort out an example by myself:
The code copy is as follows:
function fun(num, callback){
if(num<0) {
alert("Call the A-level function to handle!");
alert("Data cannot be negative, input error!");
}else if(num==0){
alert("Call the A-level function to handle!");
alert("This data item does not exist!");
}else{
alert("Call B-level function to process!");
callback(1);
}
}
function test(){
var num=document.getElementById("score").value;
fun(num,function(back){ //Anonymous B-layer processing function
alert(":"+back);
if(num<2)
alert("number is 1");
else if(num<=3)
alert("The number is 2 or 3!");
else
alert("number greater than 3!");
})
}
When the function starts to execute fun, first go to determine whether num is a negative number or zero, otherwise execute the B-layer processing function alert(":"+back); output 1, and determine it as <2, <=3, >3, etc.
Experience tips:
It is best to ensure that the callback exists and must be a function reference or function expression:
The code copy is as follows:
(callback && typeof(callback) === "function") && callback();
The code copy is as follows:
var obj={
init : function(callback){
//TODO ...
if(callback && typeof(callback) === "function") && callback()){
callback('init...');//Callback
}
}
Finally, about why you need to use a callback function? The following metaphor is very vivid and interesting.
If you have something to do, go to the next dormitory to find a classmate and find that the person is not there, what should you do?
Method 1: Go to the next dormitory every few minutes to see if the person is there
Method 2: Please call someone in the same dormitory with him and call you when you see him come back
The former is polling, and the latter is callback.
Then you say, can I wait directly in the dormitory next door until my classmates come back?
Yes, but in this way, you could have saved time to do other things, but now you have to waste it on waiting. Turn the original non-blocking asynchronous call into a blocking synchronous call.
JavaScript callbacks are used in asynchronous call scenarios, and the performance of using callbacks is better than polling.