Home Web Front-end JS Tutorial Detailed explanation of javascript callback function_Basic knowledge

Detailed explanation of javascript callback function_Basic knowledge

May 16, 2016 pm 04:31 PM
javascript Callback

Callback function definition

The callback function is a function called through a function pointer. If you pass a function pointer (address) as a parameter to another function, and when this pointer is used to call the function it points to, we say it is a callback function. The callback function is not called directly by the implementer of the function, but is called by another party when a specific event or condition occurs to respond to the event or condition.

In JavaScript, the specific definition of a callback function is: function A is passed as a parameter (function reference) to another function B, 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 for asynchronous use. Callback is often used in general synchronous (blocking) scenarios, such as requiring the execution of a callback function after performing certain operations.

Example
An example of using callbacks in synchronization (blocking), the purpose is to execute func2 after the execution of func1 code is completed.

Copy code The code is as follows:

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

Usage occasions of callback function
Resource loading: execute callback after dynamically loading js files, execute callback after loading iframe, ajax operation callback, execute callback after image loading is completed, AJAX, etc.

DOM events and Node.js events are based on the callback mechanism (Node.js callbacks may have problems with multi-layer callback nesting).
The delay time of setTimeout is 0. This hack is often used. The function called by settimeout is actually the embodiment of a callback

Chained calls: When chained, it is easy to implement chained calls in the assignor (setter) method (or in a method that does not return a value itself), but the getter (getter) is relatively difficult to implement. Implement chained calls, because you need the valuer to return the data you need instead of this pointer. If you want to implement a chained method, you can use a callback function to implement it

The function calls of setTimeout and setInterval get their return values. Since both functions are asynchronous, that is, their calling sequence is relatively independent of the main process of the program, there is no way to wait for their return values ​​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, so it is meaningless to use return, and callback can only be used. The meaning of callback is to notify the agent function of the result of timer execution for timely processing.

Functions are also objects

If you want to understand the callback function, you must first clearly understand the rules of the function. In JavaScript, functions are weird, but they are indeed objects. To be precise, a function is a Function object created using the Function() constructor. The Function object contains a string that contains the JavaScript code of the function. If you are coming from C or Java, this may seem strange. How can the code be a string? But with javascript, this is commonplace. The distinction between data and code is blurry.

Copy code The code is as follows:

//You can create functions like this
var fn = new Function("arg1", "arg2", "return arg1 * arg2;");
fn(2, 3); //6

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

Passing function as callback

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

Copy code The code is as follows:

function fn(arg1, arg2, callback){
var num = Math.ceil(Math.random() * (arg1 - arg2) arg2);
​ callback(num);//Transfer the result
}

fn(10, 20, function(num){
console.log("Callback called! Num: " num);
});//The result is a random number between 10 and 20

Maybe this seems cumbersome or even a bit stupid. Why don't you return the results normally? But when you have to use a callback function, you may not think so!

Stay out of the way

Traditional functions input data in the form of parameters and use return statements to return values. Theoretically, there is a return statement at the end of the function, which is structurally: an input point and an output point. This is easier to understand. A function is essentially a mapping of the implementation process between input and output.

However, when the function implementation process is very long, do you choose to wait for the function to complete processing, or use a callback function for asynchronous processing? In this case, it becomes crucial to use callback functions, for example: AJAX requests. If you use a callback function for processing, the code can continue to perform other tasks without waiting in vain. In actual development, asynchronous calls are often used in JavaScript, and it is even highly recommended here!

Below is a more comprehensive example of using AJAX to load an XML file, and uses the call() function to call the callback function in the context of the requested object.

Copy code The code is as follows:

function fn(url, callback){
var httpRequest; //Create XHR
httpRequest = window.XMLHttpRequest ? new XMLHttpRequest() : 
   window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP"    ): undefined;//Functional detection for IE
 
httpRequest.onreadystatechange = function(){
If(httpRequest.readystate === 4
&& httprequest.status === 200) {// Status judgment
​​​​​ callback.call(httpRequest.responseXML);
}
};
httpRequest.open("GET", url);
httpRequest.send();
}

fn("text.xml", function(){   //Call function
console.log(this); //Output after this statement
});

console.log("this will run before the above callback."); //This statement is output first

Our requests are processed asynchronously, which means that when we start the request, we tell them to call our function when they are completed. In actual situations, the onreadystatechange event handler must also consider the situation of request failure. Here 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 and therefore will not be executed immediately.

Eventually, the second console.log statement is executed first because the callback function is not executed until the request is completed.

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

Copy code The code is as follows:

function foo(){
var a = 10;
Return function(){
        a *= 2;
         return a;                                    };  
}
var f = foo();
f(); //return 20.
f(); //return 40.

When the function is called externally, the variable a can still be accessed. This is all because scope in JavaScript is lexical. Functions run in the scope in which they are defined (the scope inside foo in the above example), not the scope in which the function is run. As long as f is defined in foo, it can access all variables defined in foo, even if the execution of foo has ended. Because its scope will be saved, but only the returned function can access this saved scope. Returning a nested anonymous function is the most common way to create closures.

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to write java callback function How to write java callback function Jan 09, 2024 pm 02:24 PM

The writing methods of java callback function are: 1. Interface callback, define an interface, which contains a callback method, use the interface as a parameter where the callback needs to be triggered, and call the callback method at the appropriate time; 2. Anonymous inner class callback , you can use anonymous inner classes to implement callback functions to avoid creating additional implementation classes; 3. Lambda expression callbacks. In Java 8 and above, you can use Lambda expressions to simplify the writing of callback functions.

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Basic syntax and application of callback functions in Java Basic syntax and application of callback functions in Java Jan 30, 2024 am 08:12 AM

Introduction to the basic writing and usage of Java callback functions: In Java programming, the callback function is a common programming pattern. Through the callback function, a method can be passed as a parameter to another method, thereby achieving indirect call of the method. The use of callback functions is very common in scenarios such as event-driven, asynchronous programming and interface implementation. This article will introduce the basic writing and usage of Java callback functions, and provide specific code examples. 1. Definition of callback function A callback function is a special function that can be used as a parameter

See all articles