7/30/2019 Whats is Callback Function
1/19
David Robinson
14.9k 2 14 37
Yahoo-Me
344 3 14
27 Answers
How to explain callbacks in plain English? How are they different from calling one function from another
function taking some context from the calling function? How can their power be explained to a novice
programmer?
function callback
edited Sep 14 at 22:07 asked Mar 7 at 5:25
80% accept rate
4 its good question Balaswamy vaddemanMar 7 at 5:46
I believe the scientific name for it is continuation-passing style. You can search for this on wiki. lightbladeMar
11 at 4:48
There's some good answers to an identical question on Quora also dbrMar 11 at 4:56
5 I wonder how come so many answers have "-1" (I could easily guess though :)) AoeAoeMar 11 at 17:25
1 Relevant question: stackoverflow.com/questions/824234/what-is-a-callback-function moodywoodyMar 12 at
5:26
show 1 more comment
feedback
Often an application needs to execute different functions based upon its context/state. For this, we use a
variable where we would store the information about the function to be called. According to its need the
application will set this variable with the information about function to be called and will call the function using
the same variable.
In javascript, the example is below. Here we use method argument as a variable where we store information
about function.
How to explain callbacks in plain english? How are they different from
function from another function?
ttp://stackoverflow.com/questions/9596276/how-to-explain-callbacks-in-plain-english-how-are-they-different-from-callin
7/30/2019 Whats is Callback Function
2/19
Niraj Nawanit
662 3 10
function processArray(arr, callback) {
var resultArr = new Array();
for (var i = arr.length-1; i >= 0; i--)
resultArr[i] = callback(arr[i]);
return resultArr;
}
var arr = [1, 2, 3, 4];
var arrReturned = processArray(arr, function(arg) {return arg * -1;});// arrReturned would be [-1, -2, -3, -4]
edited Mar 10 at 8:24 answered Mar 10 at 8:17
feedback
I am going to try to keep this dead simple. A "callback" is any function that is called by another function which
takes the first function as a parameter. A lot of the time, a "callback" is a function that is called when
something happens. That something can be called an "event" in programmer-speak.
Imagine this scenario: You are expecting a package in a couple of days. The package is a gift for your
neighbor. Therefore, once you get the package, you want it brought over the the neighbors. You are out of
town, and so you leave instructions for your spouse.
You could tell her to get the package and bring it to the neighbors. If your spouse was as stupid as a
computer, she would sit at the door and wait for the package until it came (NOT DOING ANYTHING ELSE)and then once it came she would bring it over to the neighbors. But there's a better way. Tell your wife that
ONCE she receives the package, she should bring it over the neighbors. Then, she can go about life
normally UNTIL she receives the package.
In our example, the receiving of the package is the "event" and the bringing it to the neighbors is the
"callback". Your wife "runs" your instructions to bring the package over only when the package arrives. Much
better!
This kind of thinking is obvious in daily life, but computers don't have the same kind of common sense.
Consider how programmers normally write to a file:
fileObject = open(file)
# now that we have WAITED for the file to open, we can write to it
fileObject.write("We are writing to the file.")
# now we can continue doing the other, totally unrelated things our program doe
Here, we WAIT for the file to open, before we write to it. This "blocks" the flow of execution, and our program
cannot do any of the other things it might need to do! What if we could do this instead:
# we pass writeToFile (A CALLBACK FUNCTION!) to the open function
ttp://stackoverflow.com/questions/9596276/how-to-explain-callbacks-in-plain-english-how-are-they-different-from-callin
7/30/2019 Whats is Callback Function
3/19
Josh Imhoff
617 1 2 7
fileObject = open(file, writeToFile)
# execution continues flowing -- we don't wait for the file to be opened
# ONCE the file is opened we write to it, but while we wait WE CAN DO OTHER THI
It turns out we do this with some languages and frameworks. It's pretty cool! Check out Node.js to get some
real practice with this kind of thinking.
edited Apr 2 at 17:44 answered Mar 11 at 4:24
6 Good explanation!!! I am hoping for a wiki kinda answer for this question. Arkid MitraMar 11 at 4:36
1 This is correct, but does not cover all common use cases for callbacks. Often you use callbacks when you
need to call a function with arguments which would be processed in the process of another function. For
example in PHP array_filter() and array_map() take callbacks to be called in a loop. Haralan DobrevMar 13
at 23:33
feedback
How to explain callbacks in plain English?
In plain English, a callback function is like a Worker who "calls back" to his Manager when he has
completed a Task.
How are they different from calling one function from another function taking some context from the
calling function?
It is true that you are calling a function from another function, but the key is that the callback is treated like an
Object, so you can change which Function to call based on the state of the system (like the Strategy Design
Pattern).
How can their power be explained to a novice programmer?
The power of callbacks can easily be seen in AJAX-style websites which need to pull data from a server.
Downloading the new data may take some time. Without callbacks, your entire User Interface would "freeze
up" while downloading the new data, or you would need to refresh the entire page rather than just part of it.
With a callback, you can insert a "now loading" image and replace it with the new data once it is loaded.
Some code without a callback:
function grabAndFreeze() {
showNowLoading(true);var jsondata = getData('http://yourserver.com/data/messages.json');
/* User Interface 'freezes' while getting data */
processData(jsondata);
showNowLoading(false);
do_other_stuff(); // not called until data fully downloaded
}
ttp://stackoverflow.com/questions/9596276/how-to-explain-callbacks-in-plain-english-how-are-they-different-from-callin
7/30/2019 Whats is Callback Function
4/19
function processData(jsondata) { // do something with the data
var count = jsondata.results ? jsondata.results.length : 0;
$('#counter_messages').text(['Fetched', count, 'new items'].join(' '));
$('#results_messages').html(jsondata.results || '(no new messages)');
}
With Callback:
Here is an example with a callback, using jQuery's getJSON:
function processDataCB(jsondata) { // callback: update UI with results
showNowLoading(false);
var count = jsondata.results ? jsondata.results.length : 0;
$('#counter_messages').text(['Fetched', count, 'new items'].join(' '));
$('#results_messages').html(jsondata.results || '(no new messages)');
}
function grabAndGo() { // and don't freeze
showNowLoading(true);
$('#results_messages').html(now_loading_image);
$.getJSON("http://yourserver.com/data/messages.json", processDataCB);
/* Call processDataCB when data is downloaded, no frozen User Interface! */do_other_stuff(); // called immediately
}
With Closure:
Often the callback needs to access state from the calling function using a closure , which is like the
Worker needing to get information from the Manager before he can complete his Task. To create the
closure , you can inline the function so it sees the data in the calling context:
/* Grab messages, chat users, etc by changing dtable. Run callback cb when done.
function grab(dtable, cb) {
if (null == dtable) { dtable = "messages"; }
var uiElem = "_" + dtable;showNowLoading(true, dtable);
$('#results' + uiElem).html(now_loading_image);
$.getJSON("http://yourserver.com/user/"+dtable+".json", cb || function (jso
// Using a closure: can "see" dtable argument and uiElem variables above.
var count = jsondata.results ? jsondata.results.length : 0,
counterMsg = ['Fetched', count, 'new', dtable].join(' '),
// no new chatters/messages/etc
defaultResultsMsg = ['(no new ', dtable, ')'].join('');
showNowLoading(false, dtable);
$('#counter' + uiElem).text(counterMsg);
$('#results'+ uiElem).html(jsondata.results || defaultResultsMsg);
});
/* User Interface calls cb when data is downloaded */
do_other_stuff(); // called immediately
}
Usage:
// update results_chatters when chatters.json data is downloaded:
ttp://stackoverflow.com/questions/9596276/how-to-explain-callbacks-in-plain-english-how-are-they-different-from-callin
7/30/2019 Whats is Callback Function
5/19
user508994283 1 5
grab("chatters");
// update results_messages when messages.json data is downloaded
grab("messages");
// call myCallback(jsondata) when "history.json" data is loaded:
grab("history", myCallback);
Closure
Finally, here is a definition of closure from Douglas Crockford:
Functions can be defined inside of other functions. The inner function has access to the vars and parameters
of the outer function. If a reference to an inner function survives (for example, as a callback function), the
outer function's vars also survive.
See also:
http://javascript.crockford.com/survey.html
http://api.jquery.com/jQuery.when/
http://api.jquery.com/jQuery.getJSON/
http://github.com/josher19/jQuery-Parse
answered Mar 12 at 4:12
+1 Nice and clear. ChristophMar 13 at 18:38
although not "plain english" -- there is code inside... (just because Yahoo-Me asked for it) f13oMar 13 at 21:09
+1. The first paragraph is bang on the money. However, the rest of it goes into computer science jargon quite
quickly. TarkaDaalMar 16 at 10:14
feedback
In non-programmer terms, a callback is a fill-in-the-blank in a program.
A common item on many paper forms is "Person to call in case of emergency". There is a blank line there.
You write in someone's name and phone number. If an emergency occurs, then that person gets called.
Everyone gets the same blank form, but
Everyone can write a different emergency contact number.
This is key. You do not change the form (the code, usually someone else's). However you can fill in missing
pieces of information (yournumber).
Example 1:
Callbacks are used as customized methods, possibly for adding to/changing a program's behavior. For
example, take some C code that performs a function, but does not know how to print output. All i t can do is
make a string. When it tries to figure out what to do with the string, it sees a blank line. But, the programmer
gave you the blank to write your callback in!
In this example, you do not use a pencil to fill in a blank on a sheet of paper, you use the function
set_print_callback(the_callback) .
ttp://stackoverflow.com/questions/9596276/how-to-explain-callbacks-in-plain-english-how-are-they-different-from-callin
7/30/2019 Whats is Callback Function
6/19
Syphyreal
113 3
Gargi Srinivas
441 1 4
The blank variable in the module/code is the blank line,
set_print_callback is the pencil,
and the_callback is your information you are filling in.
You've now filled in this blank line in the program. Whenever it needs to print output, it will look at that blank
line, and follow the instructions there (i.e. call the function you put there.) Practically, this allows the
possibility of printing to screen, to a log file, to a printer, over a network connection, or any combination
thereof. You have filled in the blank with what you want to do.
Example 2:
When you get told you need to call an emergency number, you go and read what is written on the paper
form, and then call the number you read. If that line is blank nothing will be done.
Gui programming works much the same way. When a button is clicked, the program needs to figure out what
to do next. It goes and looks for the callback. This callback happens to be in a blank labeled "Here's what
you do when Button1 is clicked"
Most IDEs will automatically fill in the blank for you (write the basic method) when you ask it to (e.g.
button1_clicked ). However that blank can have any method you darn well please. You could call the
method run_computations or butter_the_biscuits as long as you put that callback's name in the
proper blank. You could put "555-555-1212" in the emergency number blank. It doesn't make much sense,
but it's permissible.
Final note: That blank line that you're filling in with the callback? It can be erased and re-written at will.
(whether you should or not is another question, but that is a part of their power)
answered Mar 12 at 17:13
I think this is the clearest explanation here. pablaasmoMar 14 at 7:35
feedback
Always better to start with an example :).
Let's assume you have two modules A and B.
You want module A to be notified when some event/condition occurs in module B. However, module B has
no idea about your module A. All it knows is an address to a particular function (of module A) through a
function pointer that is provided to it by module A.
So all B has to do now, is "callback" into module A when a particular event/condition occurs by using the
function pointer. A can do further processing inside the callback function.
*) A clear advantage here is that you are abstracting out everything about module A from module B. Module
B does not have to care who/what module A is.
answered Mar 7 at 5:44
ttp://stackoverflow.com/questions/9596276/how-to-explain-callbacks-in-plain-english-how-are-they-different-from-callin
7/30/2019 Whats is Callback Function
7/19
tovmeod
362 1 9
effigy
51 1
Hanno Fietz
6,214 8 45 139
feedback
Johny the programmer needs a stapler, so he goes down to the office supply department and ask for one,
after filling the request form he can either stand there and wait for the clerk go look around the warehouse for
the stapler (like a blocking function call) or go do something else meantime.
since this usually takes time, johny puts a note together with the request form asking them to call him when
the stapler is ready for pickup, so meantime he can go do something else like napping on his desk.
answered Mar 11 at 14:56
feedback
You feel ill so you go to the doctor. He examines you and determines you need some medication. He
prescribes some meds and calls the prescription into your local pharmacy. You go home. Later yourpharmacy calls to tell you your prescription is ready. You go and pick it up.
answered Mar 11 at 3:33
feedback
There's two points to explain, one is how a callback works (passing around a function that can be called
without any knowledge of its context), the other what it's used for (handling events asynchronously).
The analogy of waiting for a parcel to arrive that has been used by other answers is a good one to explain
both. In a computer program, you would tell the computer to expect a parcel. Ordinarily, it would now sit
there and wait (and do nothing else) until the parcel arrives, possibly indefinitely if it never arrives. To
humans, this sounds silly, but without further measures, this is totally natural to a computer.
Now the callback would be the bell at your front door. You provide the parcel service with a way to notify you
of the parcel's arrival without them having to know where (even if) you are in the house, or how the bell
works. (For instance, some "bells" actually dispatch a phone call.) Because you provided a "callback
function" that can be "called" at any time, out of context, you can now stop sitting at the front porch and
"handle the event" (of parcel arrival) whenever it's time.
answered Mar 11 at 9:05
feedback
You have some code you want to run. Normally, when you call it you are then waiting for it to be finished
ttp://stackoverflow.com/questions/9596276/how-to-explain-callbacks-in-plain-english-how-are-they-different-from-callin
7/30/2019 Whats is Callback Function
8/19
Andrew Ducker
574 3 6 20
Luciano
371 1 9
before you carry on (which can cause your app to go grey/produce a spinning time for a cursor).
An alternative method is to run this code in parallel and carry on with your own work. But what if your original
code needs to do different things depending on the response from the code it called? Well, in that case you
can pass in the name/location of the code you want it to call when it's done. This is a "call back".
Normal code: Ask for Information->Process Information->Deal with results of Processing->Continue to do
other things.
With callbacks: Ask for Information->Process Information->Continue to do other things. And at some laterpoint->Deal with results of Processing.
answered Mar 11 at 11:24
feedback
Without callback neither others special programming resources (like threading, and others), a program is
exactly a sequence of instructions which are executed sequentially one after the other, and even with
a kind of "dynamic behavior" determined by certain conditions, all possible scenarios shall be previously
programmed.
So, If we need to provide a real dynamic behavior to a program we can use callback. With callback you can
instructs by parameters, a program to call an another program providing some previously defined
parameters and can expects some results (this is the contract or operation signature), so these results can
be produced/processed by third-party program which wasn't previously known.
This technique is the foundation of polymorphism applied to programs, functions, objects and all
others unities of code ran by computers.
The human world used as example to callback is nice explained when you are doing some job, lets suppose
you are a painter (here you are the main program, that paints) and call your client sometimes to ask him to
approve the result of your job, so, he decides if the picture is good (your client is the third-party program).
In the above example you are a painter and "delegate" to others the job to approve the result, the picture is
the parameter, and each new client (the called-back "function") changes the result of your work deciding
what he wants about the picture (the decision made by the clients are the returned result from the "callback
function").
I hope this explanation can be useful.
edited Mar 15 at 13:41 answered Mar 13 at 22:44
feedback
Let's pretend you were to give me a potentially long-running task: get the names of the first five unique
people you come across. This might take days if I'm in a sparsely populated area. You're not really interested
in sitting on your hands while I'm running around so you say, "When you've got the list, call me on my cell
and read it back to me. Here's the number.".
ttp://stackoverflow.com/questions/9596276/how-to-explain-callbacks-in-plain-english-how-are-they-different-from-callin
7/30/2019 Whats is Callback Function
9/19
steamer25
2,864 7 16
You've given me a callback reference--a function that I'm supposed to execute in order to hand off further
processing.
In JavaScript it might look something like this:
var lottoNumbers = [];
var callback = function(theNames) {
for (var i=0; i
7/30/2019 Whats is Callback Function
10/19
Nael El Shawwa
300 1 8
David Casseres
34 4
Optimist
269 1 5
Hope that helps!
answered Mar 12 at 3:44
feedback
A callback is a function that will be called by a second function. This second function doesn't know in
advance what function it will call. So the identityof the callback function is stored somewhere, or passed to
the second function as a parameter. This "identity," depending on the programming language, might be the
address of the callback, or some other sort of pointer, or it might be the name of the function. The principal is
the same, we store or pass some information that unambiguously identifies the function.
When the time comes, the second function can call the callback, supplying parameters depending on the
circumstances at that moment. It might even choose the callback from a set of possible callbacks. The
programming language must provide some kind of syntax to allow the second function to call the callback,
knowing its "identity."
This mechanism has a great many possible uses. With callbacks, the designer of a function can let it be
customized by having it call whatever callbacks are provided. For example, a sorting function might take a
callback as a parameter, and this callback might be a function for comparing two elements to decide which
one comes first.
By the way, depending on the programming language, the word "function" in the above discussion might be
replaced by "block," "closure," "lambda," etc.
answered Mar 13 at 20:15
feedback
A callback is a method that is scheduled to be executed when a condition is met.
An "real world" example is a local video game store. You are waiting for Half-Life 3. Instead of going to the
store every day to see if it is in, you register your email on a list to be notified when the game is available.
The email becomes your "callback" and the condition to be met is the game's availability.
A "programmers" example is a web page where you want to perform an action when a button is clicked. You
register a callback method for a button and continue doing other tasks. When/if the user cicks on the button,
the browser will look at the list of callbacks for that event and call your method.
A callback is a way to handle events asynchronously. You can never know when the callback will be
executed, or if it will be executed at all. The advantage is that it frees your program and CPU cycles toperform other tasks while waiting for the reply.
edited Mar 11 at 17:21 answered Mar 11 at 17:09
ttp://stackoverflow.com/questions/9596276/how-to-explain-callbacks-in-plain-english-how-are-they-different-from-callin
7/30/2019 Whats is Callback Function
11/19
Gulshan
500 6 19
feedback
For teaching callbacks, you have to teach the pointer first. Once the students understand the idea of pointer
to a variable, idea of callbacks will get easier. Assuming you are using C/C++, these steps can be followed.
First show your students how to use and manipulate variables using pointers alongside using the
normal variable identifiers.
Then teach them there are things that can be done only with pointers(like passing a variable by
reference).
Then tell them how executable code or functions are just like some other data(or variables) in the
memory. So, functions also have addresses or pointers.
Then show them how functions can be called with function pointers and tell these are called callbacks.
Now, the question is, why all these hassle for calling some functions? What is the benefit? Like data
pointers, function pointer aka callbacks has some advantages over using normal identifiers.
The first one is, function identifiers or function names cannot be used as normal data. I mean, you
cannot make a data structure with functions(like an array or a linked list of functions). But with
callbacks, you can make an array, a linked list or use them with other data like in dictionary of key-value
pairs or trees, or any other things. This is a powerful benefit. And other benefits are actually child of this
one.The most common use of callbacks is seen in event driver programming. Where one or more functions
are executed based on some incoming signal. With callbacks, a dictionary can be maintained to map
signals with callbacks. Then the input signal resolution and execution of corresponding code become
much easier.
The second use of callbacks coming in my mind is higher order functions. The functions which takes
other functions as input arguments. And to send functions as arguments, we need callbacks. An
example can be a function which take an array and a callback. Then it performs the callback on each of
the item of the array and return the results in another array. If we pass the function a doubling callback,
we get a doubled valued array. If we pass a squaring callback, we get squares. For square roots, just
send appropriate callback. This cannot be done with normal functions.
There might many more things. Involve the students and they will discover. Hope this helps.
answered Mar 13 at 18:31
1 My another answer related to this topic in programmers.SE programmers.stackexchange.com/a/75449/963
GulshanMar 13 at 18:34
feedback
ttp://stackoverflow.com/questions/9596276/how-to-explain-callbacks-in-plain-english-how-are-they-different-from-callin
7/30/2019 Whats is Callback Function
12/19
pete
21 1
A callback is a self-addressed stamped envelope. When you call a function, that is like sending a letter. If you
want that function to call another function you provide that information in the form of a reference or address.
answered Mar 14 at 2:27
feedback
ttp://stackoverflow.com/questions/9596276/how-to-explain-callbacks-in-plain-english-how-are-they-different-from-callin
7/30/2019 Whats is Callback Function
13/19
gatlin
89 5
Imagine a friend is leaving your house, and you tell her "Call me when you get home so that I know you
arrived safely"; that is (literally) a call back. That's what a callback function is, regardless of language. You
want some procedure to pass control back to you when it has completed some task, so you give it a function
to use to call back to you.
In Python, for example,
grabDBValue( (lambda x: passValueToGUIWindow(x) ))
grabDBValue could be written to only grab a value from a database and then let you specify what to
actually do with the value, so it accepts a function. You don't know when or if grabDBValue will return, but
if/when it does, you know what you want it to do. Here, I pass in an anonymous function (or lambda) that
sends the value to a GUI window. I could easily change the behavior of the program by doing this:
grabDBValue( (lambda x: passToLogger(x) ))
Callbacks work well in languages where functions are first class values, just like the usual integers, character
strings, booleans, etc. In C, you can "pass" a function around by passing around a pointer to it and the caller
can use that; in Java, the caller will ask for a static class of a certain type with a certain method name since
there are no functions ("methods," really) outside of classes; and in most other dynamic languages you can
just pass a function with simple syntax.
Protip:
In languages with lexical scoping (like Scheme or Perl) you can pull a trick like this:
my $var = 2;
my $val = someCallerBackFunction(sub callback { return $var * 3; });
# Perlistas note: I know the sub doesn't need a name, this is for illustration
$val in this case will be 6 because the callback has access to the variables declared in the lexical
environment where it was defined. Lexical scope and anonymous callbacks are a powerful combination
warranting further study for the novice programmer.
answered Mar 11 at 3:57
+1. I actually quite like this answer. The explanation of what a callback is, is simple and concise. TarkaDaalMar
16 at 10:08
feedback
A metaphorical explanation:
I have a parcel I want delivered to a friend, and I also want to know when my friend receives it.
So I take the parcel to the post office and ask them to deliver it. If I want to know when my friend receives the
parcel, I have two options:
(a) I can wait at the post office until it is delivered.
ttp://stackoverflow.com/questions/9596276/how-to-explain-callbacks-in-plain-english-how-are-they-different-from-callin
7/30/2019 Whats is Callback Function
14/19
tonylo
1,638 2 13 19
Andrei Vajna II
1,007 1 8 21
yunzen
4,420 1 10 29
(b) I will get an email when it is delivered.
Option (b) is analogous to a callback.
answered Mar 11 at 4:23
feedback
Plain and simple: A callback is a function that you give to another function, so that it can callit.
Usually it is called when some operation is completed. Since you create the callback before giving it to the
other function, you can initialize it with context information from the call site. That is why it is named a
call*back* - the first function calls back into the context from where it was called.
answered Mar 14 at 16:34
feedback
I think it's an rather easy task to explain.
At first callback are just ordinary functions.
And the further is, that we call this function (let's call it A) from inside another function (let's call it B).
The magic about this is that I decide,which function should be called by the function from outside B.
At the time I write the function B I don't know which callback function should be called. At the time I call
function B I also tell this function to call function A. That is all.
answered Mar 16 at 16:36
feedback
Think of a method as giving a task to a coworker. A simple task might be the following:
Solve these equations:
x + 2 = y
2 * x = 3 * y
Your coworker diligently does the math and gives you the following result:
x = -6
y = -4
But your coworker has a problem, he doesn't always understand notations, such as ^ , but he does
ttp://stackoverflow.com/questions/9596276/how-to-explain-callbacks-in-plain-english-how-are-they-different-from-callin
7/30/2019 Whats is Callback Function
15/19
Guvante
6,459 8 30
understand them by their description. Such as exponent . Everytime he finds one of these you get back
the following:
I don't understand "^"
This requires you to rewrite your entire instruction set again after explaining what the character means to
your coworker, and he doesn't always remember in between questions. And he has difficulty remembering
your tips as well, such as just ask me. He always follows your written directions as best he can however.
You think of a solution, you just add the following to all of your instructions:
If you have any questions about symbols, call me at extension 1234 and I will t
Now whenever he has a problem he calls you and asks, rather than giving you a bad response and making
the process restart.
answered Mar 16 at 22:06
feedback
What Is a Callback Function?
The simple answer to this first question is that a callback function is a function that is called through a
function pointer. If you pass the pointer (address) of a function as an argument to another, when that pointer
is used to call the function it points to it is said that a call back is made.
Callback function is hard to trace, but sometimes it is very useful. Especially when you are designing
libraries. Callback function is like asking your user to gives you a function name, and you will call that
function under certain condition.
For example, you write a callback timer. It allows you to specified the duration and what function to call, and
the function will be callback accordingly. Run myfunction() every 10 seconds for 5 times
Or you can create a function directory, passing a list of function name and ask the library to callback
accordingly. Callback success() if success, callback fail() if failed.
Lets look at a simple function pointer example
void cbfunc()
{
printf("called");
}
int main ()
{/* function pointer */
void (*callback)(void);
/* point to your callback function */
callback=(void *)cbfunc;
/* perform callback */
callback();
return 0;
ttp://stackoverflow.com/questions/9596276/how-to-explain-callbacks-in-plain-english-how-are-they-different-from-callin
7/30/2019 Whats is Callback Function
16/19
Sachin Mhetre
1,849 1 7 26
Nishant
365 2 11
}
How to pass argument to callback function?
Observered that function pointer to implement callback takes in void *, which indicates that it can takes in
any type of variable including structure. Therefore you can pass in multiple arguments by structure.
typedef struct myst
{
int a;
char b[10];
}myst;
void cbfunc(myst *mt)
{
fprintf(stdout,"called %d %s.",mt->a,mt->b);
}
int main()
{
/* func pointer */
void (*callback)(void *); //param
myst m;
m.a=10;
strcpy(m.b,"123"); /* point to callback function */
callback = (void*)cbfunc; /* perform callback and pass in the param
callback(&m);
return 0;
}
answered Mar 26 at 10:04
feedback
Usually we sent variables to functions . Suppose you have task where the variable needs to be processed
before being given as an argument - you can use callback .
function (var1 , var2) is the usual way .
What if I want var2 to be processed and then sent as an arguement ? function (Var1 , function2(var2) )
This is one type of callback - where function2 executes some code and returns a variable back to the initial
function .
answered Mar 7 at 5:30
feedback
ttp://stackoverflow.com/questions/9596276/how-to-explain-callbacks-in-plain-english-how-are-they-different-from-callin
7/30/2019 Whats is Callback Function
17/19
letuboy
155 4
Callbacks allows you to insert your own code into another block of code to be executed at another time, that
modifies or adds to the behavior of that other block of code to suit your needs. You gain flexibility and
customizability while being able to have more maintainable code.
Less hardcode = easier to maintain and change = less time = more business value = awesomeness.
For example, in javascript, using Underscore.js, you could find all even elements in an array like this:
var evens = _.filter([1, 2, 3, 4, 5, 6], function(num){ return num % 2 == 0; });
=> [2, 4, 6]
Example courtesy of Underscore.js: http://documentcloud.github.com/underscore/#filter
answered Mar 11 at 3:40
feedback
Imagine you need a function that returns 10 squared so you write a function:
function tenSquared() {return 10*10;}
Later you need 9 squared so you write another function:
function nineSquared() {return 9*9;}
Eventually you will replace all of these with a generic function:
function square(x) {return x*x;}
The exact same thinking applies for callbacks. You have a function that does something and when done calls
doA:
function computeA(){
...
doA(result);
}
Later you want the exact same function to call doB instead you could duplicate the whole function:
function computeB(){
...
doB(result);
}
Or you could pass a callback function as a variable and only have to have the function once:
function compute(callback){
...
callback(result);
}
ttp://stackoverflow.com/questions/9596276/how-to-explain-callbacks-in-plain-english-how-are-they-different-from-callin
7/30/2019 Whats is Callback Function
18/19
Brian Nickel
3,790 1 6 17
sokket
36 4
Balaswamy vaddeman
1,408 1 7 20
Then you just have to call compute(doA) and compute(doB).
Beyond simplifying code, it lets asynchronous code let you know it has completed by calling your arbitrary
function on completion, similar to when you call someone on the phone and leave a callback number.
answered Mar 11 at 4:00
feedback
This of it in terms of downloading a webpage:
Your program runs on a cellphone and is requesting the webpage http://www.google.com. If you write your
program synchronously, the function you write to download the data will be running continuously until all the
data is download. This means your UI will not refresh and will basically appear frozen. If you write your
program using callbacks, you request the data and say "execute this function when you've finished." This
allows the UI to still allow user interaction while the file is downloading. Once the webpage has finished
downloading, your result function (callback) is called and you can handle the data.
Basically, it allows you to request something and continue executing while waiting for the result. Once the
result comes back to you via a callback function, you can pick up the operation where it left off.
answered Mar 11 at 4:07
feedback
[edited]when we have two functions say functionA and functionB,if functionA depends on functionB.
then we call functionB as a callback function.this is widely used in Spring framework.
edited Mar 12 at 4:31 answered Mar 7 at 5:56
ttp://stackoverflow.com/questions/9596276/how-to-explain-callbacks-in-plain-english-how-are-they-different-from-callin
7/30/2019 Whats is Callback Function
19/19
feedback
Not the answer you're looking for? Browse other questions tagged function callback
or ask your own question.
ttp //stackoverflowcom/questions/9596276/how to explain callbacks in plain english how are they different from callin