Home >Web Front-end >JS Tutorial >JS callback function example
When I first learned js, I was confused by the callback function. Now I look back and summarize what the callback function is.
Let’s first take a look at the English definition of callback: A callback is a function that is passed as an argument to another function and is executed after its parent function has completed.
Literally understood, the callback function is a parameter. This function is passed as a parameter to another function. After that function is executed, the passed function is executed. This process is called callback.
In fact, it’s easy to understand, right? Callback, callback, means calling back. After finishing the main function in advance, call the function passed in later. But I have read many blogs before, and they always explain the callback function in a vague and profound way.
Give an example that others have given: After the date, you send your girlfriend home. When you say goodbye, you will definitely say: "Send me a message when you get home. I'm very happy." I'm worried about you." Right? Then your girlfriend actually sent you a message after she got home. Boy, you have a chance. In fact, this is a callback process. You leave a parameter function (requiring your girlfriend to send you a message) to your girlfriend, and then your girlfriend goes home. The action of going home is the main function. She must first get home, the main function has been executed, and then execute the function passed in, and then you will receive a message.
Now you basically understand the meaning of the callback function. It’s okay if you don’t understand, we speak in code.
//定义主函数,回调函数作为参数function A(callback) { callback(); console.log('我是主函数'); }//定义回调函数function B(){ setTimeout("console.log('我是回调函数')", 3000);//模仿耗时操作 }//调用主函数,将函数B传进去A(B);//输出结果我是主函数 我是回调函数
In the above code, we first define the main function and callback function, and then call the main function and pass the callback function in.
When defining the main function, we let the code execute the callback() callback function first, but the output result is the content of the callback function output later. This means that the main function does not need to wait for the callback function to finish executing, and can continue to execute its own code. Therefore, callback functions are generally used for time-consuming operations. For example, ajax request, such as processing files, etc.
This article explains JS callback function examples. For more related content, please pay attention to the php Chinese website.
Related recommendations:
Inheritance implementation of js
js implements sliding the mobile HTML5 page to the bottom to trigger content loading
##JS controls the text box to prohibit the input of special characters
The above is the detailed content of JS callback function example. For more information, please follow other related articles on the PHP Chinese website!