The recent study of JavaScript callback functions, the learning experience of their own collation, not necessarily correct.
callback function Concept: A callback is a function, that is, passed as an argument to another function and are executed after its parent functio N has completed.
The Chinese explanation is that function A has a parameter, which is a function B, and executes function B after function a finishes executing. Then this process is called a callback.
The callback function can be implemented synchronously, or it can be implemented asynchronously, and the callback function defines that the callback is primarily for asynchronous mode.
One, synchronous callback
Function F1 (callback) {callback (); Console.log (' F1 ');} function F2 () {console.log (' F2 ');} F1 (F2);
The above synchronous callback code, the execution result is as follows:
In the synchronous callback process, when the program does not complete F1, the callback function F2 is executed, which contradicts the callback definition. Therefore, the synchronization process uses a callback function that does not make sense, and the synchronization process does not recommend using callback functions.
There is no need to use callbacks to implement the above features, which can be implemented using other code:
Function F1 () {F2 (); Console.log (' F1 ');} function F2 () {console.log (' F2 ');} F1 ();
Second, asynchronous callbacks
You have something to go to the next bedroom to find classmates, found that people are not, please with his bedroom, see him back when called you, this is the callback. In layman's words, after executing the function F1 (), the callback function F2 (), F2 () functions like the notification Main program: F1 () executes, and you can do other things.
Function F1 (callback) {SetTimeout (function () {//F1 task code callback (); }, 1000);} function F2 () {console.log (' F1 execution done, you can do other things ');} F1 (F2);
JavaScript callback function