Basic Definitions and usage of JS callback function instance analysis, and js callback function instance analysis
This article describes the basic definitions and usage of JS callback functions. We will share this with you for your reference. The details are as follows:
When I was a beginner in js, I was very dizzy by the callback function. Now I will go back and summarize what the callback function is.
Let's take A look at the definition of callback in English: a callback is A function that is passed as an argument to another function and is executed after its parent function has completed.
Literally, a callback function is a parameter that is passed to another function as a parameter. After the function is executed, it is executed and passed in. This process is called callback.
In fact, it is quite understandable, right? callback and callback are the meaning of calling back. After the main function is completed in advance, call the passed function. However, I have read many blogs and they are always confused about the explanation of callback functions.
For example, if you send your girlfriend home after the appointment, you will say, "when you get home, send me a message, I am worried about you ." No, then your girlfriend sent you a message after going home. You have a fight, young man. In fact, this is a callback process. You leave a Parameter Function (asking your girlfriend to send you a message) to your girlfriend, and then your girlfriend returns home. The main function is used to return home. She had to go back to the home first, the main function was executed, and then the passed function was executed, and then you received a message.
Now I have understood the meaning of the callback function. It doesn't matter if you don't understand it. We use code to speak.
// Define the main function. The callback function is used as the parameter function A (callback) {callback (); console. log ('I am the main function');} // defines the callback function B () {setTimeout ("console. log ('callback function') ", 3000); // simulates time-consuming operations} // calls the main function and transfers function B to A (B ); /* the output result is the main function and the callback function */
In the above Code, we first define the main function and callback function, and then call the main function to pass the callback function in.
When defining the main function, let the code first execute the callback () callback function, but the output result is the content of the callback function. This shows that the main function does not have to wait until the callback function is executed, and you can execute your own code. Therefore, callback functions are generally used for time-consuming operations. For example, ajax requests, such as processing files.