What is a callback function?

2018-12-31 05:34发布

What is a callback function?

20条回答
宁负流年不负卿
2楼-- · 2018-12-31 06:05

Callback Function A function which passed to another function as an argument.

function test_function(){       
 alert("Hello world");  
} 

setTimeout(test_function, 2000);

Note: In above example test_function used as an argument for setTimeout function.

查看更多
荒废的爱情
3楼-- · 2018-12-31 06:08

A callback function, also known as a higher-order function, is a function that is passed to another function as a parameter, and the callback function is called (or executed) inside the parent function.

$("#button_1").click(function() {
  alert("button 1 Clicked");
});

Here we have pass a function as a parameter to the click method. And the click method will call (or execute) the callback function we passed to it.

查看更多
闭嘴吧你
4楼-- · 2018-12-31 06:09

Call After would be a better name than the stupid name, callback. When or if condition gets met within a function, call another function, the Call After function, the one received as argument.

Rather than hard-code an inner function within a function, one writes a function to accept an already-written Call After function as argument. The Call After might get called based on state changes detected by code in the function receiving the argument.

查看更多
时光乱了年华
5楼-- · 2018-12-31 06:12

One important usage area is that you register one of your function as a handle (i.e. a callback) and then send a message / call some function to do some work or processing. Now after the processing is done, the called function would call our registered function (i.e. now call back is done), thus indicating us processing is done.
This wikipedia link explains quite well graphically.

查看更多
牵手、夕阳
6楼-- · 2018-12-31 06:13

A callback function is a function you specify to an existing function/method, to be invoked when an action is completed, requires additional processing, etc.

In Javascript, or more specifically jQuery, for example, you can specify a callback argument to be called when an animation has finished.

In PHP, the preg_replace_callback() function allows you to provide a function that will be called when the regular expression is matched, passing the string(s) matched as arguments.

查看更多
梦寄多情
7楼-- · 2018-12-31 06:14

A callback function is a function you pass (as a reference or a pointer) to a certain function or object. This function or object will call this function back any time later, possibly multiple times, for any kind of purpose :

  • notifying the end of a task
  • requesting comparison between two item (like in c qsort())
  • reporting progress of a process
  • notifying events
  • delegating the instanciation of an object
  • delegating the painting of an area

...

So describing a callback as a function being called at the end of another function or task is overly simplifying (even if it's a common use case).

查看更多
登录 后发表回答