Understand the javascript callback function
- 2020-05-09 18:09:58
- OfStack
Pass the function as a parameter to another function. This function is called a callback function
It is often the case that the A and B layers of a project are coordinated by different people. The A layer is responsible for funA functions, and the B layer is responsible for funcB. When the B layer wants to use the data of a module, he said to the A layer staff, I need you to provide the data that meets a certain requirement, and you can provide me with an interface.
The A says, "I'll give you the data, and it's up to B to show and process it."
Of course, the B layer cannot provide one data interface for each of your requirements. B provides one interface for A to pass.B gets the data, and B writes the function to show it.
That is, you need to work with other people, who provide the data, and you don't need to care about how they get it or how they build it. You just manipulate the data that you get. This is where the callback function needs to be used
Thus, a callback is essentially a design pattern, and the design principles of jQuery(including other frameworks) follow this pattern.
An example of using a callback in synchronization (blocking) to execute func2 after the func1 code has been executed.
var func1=function(callback){
//do something.
(callback && typeof(callback) === "function") && callback();
}
func1(func2);
var func2=function(){
}
Examples of asynchronous callbacks:
$(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 it is requested by a newly opened thread of the browser. When the state of the request changes, if a callback was previously set, the asynchronous thread generates a state change event and puts it in the JavaScript engine's processing queue for processing. See: http: / / www. phpv. net html / 1700. html
When will the callback be executed
The callback function, 1, is usually executed last in the synchronous scenario, but may not be executed in the asynchronous scenario because the event is not triggered or the condition is not satisfied.
Where to use the callback function
Resource loading: callback after loading js files dynamically, callback after loading iframe, callback after ajax operations, callback after loading images, callback after AJAX, and so on.
The DOM event and the Node.js event are based on a callback mechanism (the Node.js callback can cause problems with multiple layers of nested callbacks).
The delay time of setTimeout is 0, this hack is often used, and the function called by settimeout is actually the embodiment of an callback
Chain call: chain call, in the assignment editor (setter) method (or itself has no return value method) is easy to implement chain calls, and device (getter) values are relatively bad implementation chain calls, because you need value is return a pointer to the data you need rather than this, if you want to achieve chain method, can be done using the callback function
The function calls of setTimeout and setInterval get their return values. Because of the two functions are asynchronous, i.e., they call the main process of timing and the procedure is relatively independent, so the body inside have no way to wait until they return values, when they are open program will not stop to wait for, also will lose the meaning of setTimeout and setInterval, with return has no meaning, so can only use callback. The point of callback is to inform the agent function of the results of the timer execution for timely processing.
Collect 1 information on the Internet, you should understand, I sorted out an example:
function fun(num,callback){
if(num<0) {
alert(" call A Layer function processing !");
alert(" The data cannot be negative , Input error !");
}else if(num==0){
alert(" call A Layer function processing !");
alert(" This data item does not exist! ");
}else{
alert(" call B Layer function processing !");
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(" Numbers for 1");
else if(num<=3)
alert(" Numbers for 2 or 3 ! ");
else
alert(" Numbers greater than 3!");
})
}
When the function starts to execute fun, run to determine if num is negative or zero, otherwise execute alert(":"+back); Output 1, judge as < 2, < = 3, > 3. Etc.
Tips for experience:
It is best to ensure that the callback exists and must be a function reference or function expression:
(callback && typeof(callback) === "function") && callback();
var obj={
init : function(callback){
//TODO ...
if(callback && typeof(callback) === "function") && callback()){
callback('init...');// The callback
}
}
Finally, why use callback functions? The following metaphor is very vivid and interesting.
You have to go to the next bedroom to look for a classmate, found that the person is not in, how do you do?
Method 1, every few minutes to go to the next bedroom, see people in not
Method 2. Ask the roommate to call you when he comes back
The former is polling and the latter is a callback.
You say, I directly in the next bedroom until the students back can it?
Yes, but instead of saving time for other things, you have to waste it waiting. Turns a non-blocking asynchronous call into a blocking synchronous call.
The callbacks of JavaScript are used in asynchronous invocation scenarios and perform better with callbacks than polling.