JavaScript callback function

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.