


Detailed explanation of javascript callback function definition and usage examples
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 callback in synchronization (blocking), the purpose is to execute func2 after the execution of func1 code is completed.
var func1=function(callback){ //do something. (callback && typeof(callback) === "function") && callback(); } func1(func2); var func2=function(){ }
Use occasions of callback function
Resource loading: callback is executed after dynamic loading of js file, callback is executed after iframe is loaded, ajax operation callback, callback is executed after image loading is completed, AJAX, etc. wait.
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.
Chain call: During chain call, in the assignor (setter) method It is easy to implement chained calls in a method (or a method that does not return a value itself), but it is relatively difficult to implement chained calls with a getter, because you need the getter to return the data you need instead of this pointer , if you want to implement a chain method, you can use the callback function to implement the function calls of
setTimeout and setInterval to 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.
Function is also an object
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.
//可以这样创建函数 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 the code is literally just an object).
Passing functions as callbacks
It is easy to pass a function as a parameter.
function fn(arg1, arg2, callback){ var num = Math.ceil(Math.random() * (arg1 - arg2) + arg2); callback(num);//传递结果 } fn(10, 20, function(num){ console.log("Callback called! Num: " + num); });//结果为10和20之间的随机数
Maybe this seems cumbersome or even a bit stupid. Why not return the results normally? But when you have to use a callback function, you may not think so!
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.
function fn(url, callback){ var httpRequest; //创建XHR httpRequest = window.XMLHttpRequest ? new XMLHttpRequest() : window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP" ) : undefined;//针对IE进行功能性检测 httpRequest.onreadystatechange = function(){ if(httpRequest.readystate === 4 && httpRequest.status === 200){ //状态判断 callback.call(httpRequest.responseXML); } }; httpRequest.open("GET", url); httpRequest.send(); } fn("text.xml", function(){ //调用函数 console.log(this); //此语句后输出 }); console.log("this will run before the above callback."); //此语句先输出
We request asynchronous processing, 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.
Ultimately, 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:
function foo(){ var a = 10; return function(){ a *= 2; return a; }; } var f = foo(); f(); //return 20. f(); //return 40.
函数在外部调用,依然可以访问变量a。这都是因为javascript中的作用域是词法性的。函数式运行在定义它们的作用域中(上述例子中的foo内部的作用域),而不是运行此函数的作用域中。只要f被定义在foo中,它就可以访问foo中定义的所有的变量,即便是foo的执行已经结束。因为它的作用域会被保存下来,但也只有返回的那个函数才可以访问这个保存下来的作用域。返回一个内嵌匿名函数是创建闭包最常用的手段。
The above is the detailed content of Detailed explanation of javascript callback function definition and usage examples. For more information, please follow other related articles on the PHP Chinese website!

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

WebStorm Mac version
Useful JavaScript development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download
The most popular open source editor