What is a callback function?
Asked Answered
W

23

842

What is a callback function?

Wrote answered 5/5, 2009 at 10:18 Comment(5)
you can find here: https://mcmap.net/q/54973/-how-to-explain-callbacks-in-plain-english-how-are-they-different-from-calling-one-function-from-another-function the best explanation about callbacksFluorescent
possible duplicate of How to explain callbacks in plain english? How are they different from calling one function from another function?Fusiform
The best explanation of callback that i have ever found youtube.com/watch?v=xHneyv38JroPepsinate
A not simple explanation is available on Wikipedia. However we can say it more simply: Using the callback principle is like giving a business card to someone and telling: If you need me, call me back, the number is on the card. In programming words, a function leaves a reference of itself to another piece of code, e.g. by registering, and the other code uses this reference to call the (callback) function when appropriate, e.g. when some event occurs. In this case, a callback is also named an event handler.Senter
@mins: your analogy is I think what many think of, but is off the mark. A callback is not a reference to the caller. It's more like saying "please call my assistant". ... I guess a caller could pass itself as a callback, but that would lead to some complicated recursion.Trochanter
V
824

Developers are often confused by what a callback is because of the name of the damned thing.

A callback function is a function which is:

  • accessible by another function, and
  • is invoked after the first function if that first function completes

A nice way of imagining how a callback function works is that it is a function that is "called at the back" of the function it is passed into.

Maybe a better name would be a "call after" function.

This construct is very useful for asynchronous behaviour where we want an activity to take place whenever a previous event completes.

Pseudocode:

// A function which accepts another function as an argument
// (and will automatically invoke that function when it completes - note that there is no explicit call to callbackFunction)
funct printANumber(int number, funct callbackFunction) {
    printout("The number you provided is: " + number);
}

// a function which we will use in a driver function as a callback function
funct printFinishMessage() {
    printout("I have finished printing numbers.");
}

// Driver method
funct event() {
   printANumber(6, printFinishMessage);
}

Result if you called event():

The number you provided is: 6
I have finished printing numbers.

The order of the output here is important. Since callback functions are called afterwards, "I have finished printing numbers" is printed last, not first.

Callbacks are so-called due to their usage with pointer languages. If you don't use one of those, don't labour over the name 'callback'. Just understand that it is just a name to describe a method that's supplied as an argument to another method, such that when the parent method is called (whatever condition, such as a button click, a timer tick etc) and its method body completes, the callback function is then invoked.

Some languages support constructs where multiple callback function arguments are supported, and are called based on how the parent function completes (i.e. one callback is called in the event that the parent function completes successfully, another is called in the event that the parent function throws a specific error, etc).

Violence answered 26/9, 2011 at 1:4 Comment(16)
Your example is great but I don't see why the terminology is "callback". When is meaningOfLife "called back"?Odele
What if the function is not passed as an argument to another method, but is simply what the property of another class is set to, and which is called by that class when it so desires? Like if one class has a Function property for a logging function, and another class sets that property equal to a function that actually implements the logging. Is that still technically a callback?Wenonawenonah
@Wenonawenonah In my opinion, yes. Using the property is just a reference to the method which is passed as an argument. The parent method is called with the argument, which is a reference to a method which returns the value to be used as an argument. The going off, deriving and returning the value to be used as an argument and supplying it to the calling method for use in its logic is 'calling back'.Violence
@7SpecialGems what about the common routes used in a Node server like app.get('/filePath', function (req, res, next){//code in here})? It seems that the only task when calling app.get would be to execute the code inside the callback, so why would it be called back at a later point? What's the value in that and how does it allow the code to be asynchronous?Yelena
You know what I love and hate about JavaScript at the same time? The fact that you can freakin' declare and implement the callback function in the call to another function, e.g. doSomething(args...., doSomethingElse(){ //doSomethingElse() function body}); It looks better spaced appropriately, but, you get the point.Leishaleishmania
Hello there, about once its parent method completes, the function which this argument represents is then called. So if function is passed to another function as argument but called from the middle of parent function's runtime like parent(cb) {dostuff1(); cb(); dostuff2()} then it is not considered a callback function?Ciceronian
Where do you get the idea that the callback name is to do with pointer languages and is called 'at the back' of the function? It seems more likely to me that it is just a simple term that means the function receiving the callback function will cause the function to be called back, a bit like when you leave a phone message to somebody to call you back and give them your number.Closed
@MaxYari: IMHO, it is still considered as callback.The important thing here is that the parent functin is going to use the input function(aka callback) somehow. It can be called in the middle or at the end or if a condition is met.Monoxide
Why in this example does printANumber ever invoke or execute (whatever the right word is) callbackFunction? This looks like a peculiar syntactic design in certain languages (?): "If a function takes a function as a final parameter then execute it as a callback." Whereas in for instance F#, a function sent as a parameter doesn't spontaneously do anything--only if it's used/called in the code of the body.Azimuth
@Azimuth It executes it after printANumber is completed. An example of when this is useful if PrintANumber is some activity which executes asynchronously and you want a function of logic to be executed after this completes (whenever this completes) in a non-blocking way.Violence
@Violence thank you - but where is the meaningOfLife method invoked within the printANumber function?Bennet
This is not true at all: "is automatically invoked after that first function completes". A callback doesn't have to be executed at all, let alone automatically. In fact, it's not uncommon for callbacks to complete before the parent function completes. I very much dislike how people describe callbacks as being functions that are executed "later". It is very confusing to people who are learning about them. Simply put, callbacks are just functions that are passed in as arguments to other functions. Period. A better explanation would include explaining WHY callbacks over function references.Hatchery
I find the point that "callback does not really need to "go back", but merely execute something else" very helpful.Threecolor
When I tried to run it in console it didn't invoked callbackFunction. Why in your output it is showing ?Eaglewood
callbackFunction is never called in your example pseudo codeStaceestacey
I wish I could down-vote answers more than once. Like a bounty, but the opposite.Discomfortable
A
261

Opaque Definition

A callback function is a function you provide to another piece of code, allowing it to be called by that code.

Contrived example

Why would you want to do this? Let's say there is a service you need to invoke. If the service returns immediately, you just:

  1. Call it
  2. Wait for the result
  3. Continue once the result comes in

For example, suppose the service were the factorial function. When you want the value of 5!, you would invoke factorial(5), and the following steps would occur:

  1. Your current execution location is saved (on the stack, but that's not important)

  2. Execution is handed over to factorial

  3. When factorial completes, it puts the result somewhere you can get to it

  4. Execution comes back to where it was in [1]

Now suppose factorial took a really long time, because you're giving it huge numbers and it needs to run on some supercomputing cluster somwhere. Let's say you expect it to take 5 minutes to return your result. You could:

  1. Keep your design and run your program at night when you're asleep, so that you're not staring at the screen half the time

  2. Design your program to do other things while factorial is doing its thing

If you choose the second option, then callbacks might work for you.

End-to-end design

In order to exploit a callback pattern, what you want is to be able to call factorial in the following way:

factorial(really_big_number, what_to_do_with_the_result)

The second parameter, what_to_do_with_the_result, is a function you send along to factorial, in the hope that factorial will call it on its result before returning.

Yes, this means that factorial needs to have been written to support callbacks.

Now suppose that you want to be able to pass a parameter to your callback. Now you can't, because you're not going to be calling it, factorial is. So factorial needs to be written to allow you to pass your parameters in, and it will just hand them over to your callback when it invokes it. It might look like this:

factorial (number, callback, params)
{
    result = number!   // i can make up operators in my pseudocode
    callback (result, params)
}

Now that factorial allows this pattern, your callback might look like this:

logIt (number, logger)
{
    logger.log(number)
}

and your call to factorial would be

factorial(42, logIt, logger)

What if you want to return something from logIt? Well, you can't, because factorial isn't paying attention to it.

Well, why can't factorial just return what your callback returns?

Making it non-blocking

Since execution is meant to be handed over to the callback when factorial is finished, it really shouldn't return anything to its caller. And ideally, it would somehow launch its work in another thread / process / machine and return immediately so that you can continue, maybe something like this:

factorial(param_1, param_2, ...)
{
    new factorial_worker_task(param_1, param_2, ...);
    return;
}

This is now an "asynchronous call", meaning that when you call it, it returns immediately but hasn't really done its job yet. So you do need mechanisms to check on it, and to obtain its result when its finished, and your program has gotten more complex in the process.

And by the way, using this pattern the factorial_worker_task can launch your callback asynchronously and return immediately.

So what do you do?

The answer is to stay within the callback pattern. Whenever you want to write

a = f()
g(a)

and f is to be called asynchronously, you will instead write

f(g)

where g is passed as a callback.

This fundamentally changes the flow-topology of your program, and takes some getting used to.

Your programming language could help you a lot by giving you a way to create functions on-the-fly. In the code immediately above, the function g might be as small as print (2*a+1). If your language requires that you define this as a separate function, with an entirely unnecessary name and signature, then your life is going to get unpleasant if you use this pattern a lot.

If, on the other hand, you language allows you to create lambdas, then you are in much better shape. You will then end up writing something like

f( func(a) { print(2*a+1); })

which is so much nicer.

How to pass the callback

How would you pass the callback function to factorial? Well, you could do it in a number of ways.

  1. If the called function is running in the same process, you could pass a function pointer

  2. Or maybe you want to maintain a dictionary of fn name --> fn ptr in your program, in which case you could pass the name

  3. Maybe your language allows you to define the function in-place, possible as a lambda! Internally it is creating some kind of object and passing a pointer, but you don't have to worry about that.

  4. Perhaps the function you are calling is running on an entirely separate machine, and you are calling it using a network protocol like HTTP. You could expose your callback as an HTTP-callable function, and pass its URL.

You get the idea.

The recent rise of callbacks

In this web era we have entered, the services we invoke are often over the network. We often do not have any control over those services i.e. we didn't write them, we don't maintain them, we can't ensure they're up or how they're performing.

But we can't expect our programs to block while we're waiting for these services to respond. Being aware of this, the service providers often design APIs using the callback pattern.

JavaScript supports callbacks very nicely e.g. with lambdas and closures. And there is a lot of activity in the JavaScript world, both on the browser as well as on the server. There are even JavaScript platforms being developed for mobile.

As we move forward, more and more of us will be writing asynchronous code, for which this understanding will be essential.

Amaze answered 4/5, 2014 at 6:34 Comment(3)
Yes i understand how lambas work in javascript and ruby. And java 8 but old versions of java did not use lambas and instead used classes and i would like to know how that kind of callback works. Still a superior answer to the other.Pizza
No. Every argument that is a function isn't a callback. It could be an iterator function, or a sort function, or many other things. See the etymology of the term "callback".Pyrophosphate
Would it be fair to say that this use of callback is a form of ‘Remote Procedure Call’?Footlight
C
116

The Callback page on Wikipedia explains it very well:

In computer programming, a callback is a reference to executable code, or a piece of executable code, that is passed as an argument to other code. This allows a lower-level software layer to call a subroutine (or function) defined in a higher-level layer.

Closed answered 5/5, 2009 at 10:19 Comment(5)
And this also leads to the answer in a different way. The noun "callback" is that which has been "called back", in the same way something that's gone through shutdown has been shut down and something that's used to log in is a login.Selfdetermination
Wikipedia has actually got some really awesome programming stuff in its troves. I always felt like the term "callback" was best explained using the phrase, "I am going to call back to..."Leishaleishmania
Great explanation at javascriptissexy.com/…; which i will repost here; A callback function is a function that is passed to another function as a parameter, and the callback function is called or executed inside the otherFunction. //Note that the item in the click method's parameter is a function, not a variable.​ ​//The item is a callback function $("#btn_1").click(function() { alert("Btn 1 Clicked"); }); As you see in the preceding example, we pass a function as a parameter to the click method for it to execute –Deranged
@Odele I think the question is so simple, and the wikipedia page explains it the concept in the first paragraph there is little need for a longer answer. The top answer on here, for example, just says the same think as the first paragraph of wikipedia in different words, and to me the pseudo code doesn't show anything that the wikipedia examples do. DRY ;-)Closed
That's funny because this answer quotes Wikipedia which quotes Stack Overflow answer from 8bitjunkieLangdon
B
57

Simple Explanation by Analogy

Everyday, I get to work. The boss tells me:

Oh, and when you're done with that, I have an extra task for you:

Great. He hands me a note with a task on it - this task is a call back function. It could be anything:

ben.doWork( and_when_finished_wash_my_car)

Tomorrow it could be:

ben.doWork( and_tell_me_how_great_i_am)

The key point is that the call back must be done AFTER I finish work! You would do well to read the code contained in other answers above, which i need not repeat.

Bennet answered 29/2, 2016 at 12:26 Comment(0)
A
53

A layman response would be that it is a function that is not called by you but rather by the user or by the browser after a certain event has happened or after some code has been processed.

Alpaca answered 15/9, 2011 at 16:48 Comment(0)
T
45

A callback function is one that should be called when a certain condition is met. Instead of being called immediately, the callback function is called at a certain point in the future.

Typically it is used when a task is being started that will finish asynchronously (ie will finish some time after the calling function has returned).

For example, a function to request a webpage might require its caller to provide a callback function that will be called when the webpage has finished downloading.

Transponder answered 5/5, 2009 at 16:7 Comment(2)
In your first sentence, you say "...when a condition is met" but i thought callbacks are called when the parent function finishes executing and are not dependent of conditions (?).Gamelan
The 'certain condition' just means they generally get called for a reason, rather than at random. A callback could be called when the parent/creator is still executing - this could lead to a race condition if the programmer is not expecting it.Transponder
M
44

Callbacks are most easily described in terms of the telephone system. A function call is analogous to calling someone on a telephone, asking her a question, getting an answer, and hanging up; adding a callback changes the analogy so that after asking her a question, you also give her your name and number so she can call you back with the answer.

-- Paul Jakubik, "Callback Implementations in C++"

Marsh answered 11/1, 2014 at 1:13 Comment(3)
So my name and number is a function?Cobby
No, that'd be the analogy if "callback" was a good name for what is instead: you ask the telephone operator to make a call. The end.Mackler
What I infer from this lovely answer is that the act of "calling back" is when the callback function terminates and returns back to the parent function. Am I wrong?Foumart
L
35

I believe this "callback" jargon has been mistakenly used in a lot of places. My definition would be something like:

A callback function is a function that you pass to someone and let them call it at some point of time.

I think people just read the first sentence of the wiki definition:

a callback is a reference to executable code, or a piece of executable code, that is passed as an argument to other code.

I've been working with lots of APIs, see various of bad examples. Many people tend to name a function pointer (a reference to executable code) or anonymous functions(a piece of executable code) "callback", if they are just functions why do you need another name for this?

Actually only the second sentence in wiki definition reveals the differences between a callback function and a normal function:

This allows a lower-level software layer to call a subroutine (or function) defined in a higher-level layer.

so the difference is who you are going to pass the function and how your passed in function is going to be called. If you just define a function and pass it to another function and called it directly in that function body, don't call it a callback. The definition says your passed in function is gonna be called by "lower-level" function.

I hope people can stop using this word in ambiguous context, it can't help people to understand better only worse.

Larhondalari answered 20/7, 2012 at 10:58 Comment(5)
Your answer makes sense... but I'm having trouble picturing it. Can you give an example?Odele
@Zane Wong :: In the last you have written "The definition says your passed in function is gonna be called by "lower-level" function." Can you please explain what lower-level function indicates ? Its better if you give an example .Cirrate
An example would have been niceCirce
I think the difference between classical function call and call-back style is link to dependy direction : if module A depends upon ("uses") module B, A calls a function of B, it's not a callback. If A passes a reference to his function to B, then B call a function of A, this is a callback : the call goes backwards compare to the module dependency.Base
Mr @ZaneXY "If you just define a function and pass it to another function and called it directly in that function body, don't call it a callback." Ain't that the definition of a synchronous callback, i.e. one that get's executed immediately?Foumart
S
31
  • A function passed as an argument to another function: It's not executed immediately but "called back" later when a specific event or condition occurs.

  • Enables asynchronous programming: It allows code to continue executing other tasks while waiting for an operation to complete, preventing blocking. Use cases are:

    • Asynchronous Operations: Handling events (e.g., button clicks, network requests), timers, animations, I/O tasks.
    • Event-Driven Programming: Reacting to user interactions, system events, sensor readings.

function fetchData(url, callback) {
  // Simulate an asynchronous data fetch
  setTimeout(() => {
    const data = { message: "Hello from the server!" };
    callback(data); // Call the callback with the fetched data
  }, 2000);
}

fetchData("https://example.com", (data) => {
  console.log(data.message); // Output: "Hello from the server!" (after 2 seconds)
});

console.log("Fetching data..."); // Executes immediately
Salford answered 11/5, 2015 at 7:9 Comment(1)
A callback function is not itself a higher-order function. It is passed to a higher-order function.Closed
E
21

This makes callbacks sound like return statements at the end of methods.

I'm not sure that's what they are.

I think Callbacks are actually a call to a function, as a consequence of another function being invoked and completing.

I also think Callbacks are meant to address the originating invocation, in a kind of "hey! that thing you asked for? I've done it - just thought I would let you know - back over to you".

Eyestrain answered 27/10, 2010 at 23:18 Comment(1)
+1 for questioning Callbacks vs Return statements. I used to get caught out by this and so do many graduates who I work with.Violence
B
18

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.

Bullnecked answered 5/5, 2009 at 10:21 Comment(0)
M
17

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.

Moorish answered 19/11, 2013 at 1:40 Comment(2)
This is a great idea. I went for "called at the back" to try and explain this. I could see someone like Martin Fowler popularising "call after" as a new term for these on his seminal blog.Violence
What if it just didn't have a name at all? Wouldn't that be the least confusing? It's just a function.Widget
E
12

look at the image :)this is how it works

Main program calls library function (which might be system level function also) with callback function name. This callback function might be implemented in multiple way. The main program choose one callback as per requirement.

Finally, the library function calls the callback function during execution.

Emetine answered 23/12, 2011 at 6:29 Comment(4)
Would you mind also adding a text explanation to this? If the image vanishes, this answer loses all context.Expellant
text from other people explains it the best. the only thing i felt is lacking is the image :)Emetine
Of all the long winded descriptions I've seen here this one is the one that made me go "ahhhhh, now I see its use." Have an upvote.Soapy
Well, it doesn't have to be a library function to call you back this way. You program can create a separate thread to perform some task and trigger a callback mecanism, without an external library.Base
G
7

The simple answer to this 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

Gabelle answered 10/3, 2011 at 5:27 Comment(0)
I
7

Assume we have a function sort(int *arraytobesorted,void (*algorithmchosen)(void)) where it can accept a function pointer as its argument which can be used at some point in sort()'s implementation . Then , here the code that is being addressed by the function pointer algorithmchosen is called as callback function .

And see the advantage is that we can choose any algorithm like:

  1.    algorithmchosen = bubblesort
  2.    algorithmchosen = heapsort
  3.    algorithmchosen = mergesort   ...

Which were, say,have been implemented with the prototype:

  1.   `void bubblesort(void)`
  2.   `void heapsort(void)`
  3.   `void mergesort(void)`   ...

This is a concept used in achieving Polymorphism in Object Oriented Programming

Interstice answered 4/5, 2013 at 6:29 Comment(1)
Great explanation at javascriptissexy.com/…; which i will repost here; A callback function is a function that is passed to another function as a parameter, and the callback function is called or executed inside the otherFunction. //Note that the item in the click method's parameter is a function, not a variable.​ ​//The item is a callback function $("#btn_1").click(function() { alert("Btn 1 Clicked"); }); As you see in the preceding example, we pass a function as a parameter to the click method for it to execute –Deranged
M
4

“In computer programming, a callback is a reference to executable code, or a piece of executable code, that is passed as an argument to other code. This allows a lower-level software layer to call a subroutine (or function) defined in a higher-level layer.” - Wikipedia

Callback in C using Function Pointer

In C, callback is implemented using Function Pointer. Function Pointer - as the name suggests, is a pointer to a function.

For example, int (*ptrFunc) ();

Here, ptrFunc is a pointer to a function that takes no arguments and returns an integer. DO NOT forget to put in the parenthesis, otherwise the compiler will assume that ptrFunc is a normal function name, which takes nothing and returns a pointer to an integer.

Here is some code to demonstrate the function pointer.

#include<stdio.h>
int func(int, int);
int main(void)
{
    int result1,result2;
    /* declaring a pointer to a function which takes
       two int arguments and returns an integer as result */
    int (*ptrFunc)(int,int);

    /* assigning ptrFunc to func's address */                    
    ptrFunc=func;

    /* calling func() through explicit dereference */
    result1 = (*ptrFunc)(10,20);

    /* calling func() through implicit dereference */        
    result2 = ptrFunc(10,20);            
    printf("result1 = %d result2 = %d\n",result1,result2);
    return 0;
}

int func(int x, int y)
{
    return x+y;
}

Now let us try to understand the concept of Callback in C using function pointer.

The complete program has three files: callback.c, reg_callback.h and reg_callback.c.

/* callback.c */
#include<stdio.h>
#include"reg_callback.h"

/* callback function definition goes here */
void my_callback(void)
{
    printf("inside my_callback\n");
}

int main(void)
{
    /* initialize function pointer to
    my_callback */
    callback ptr_my_callback=my_callback;                        
    printf("This is a program demonstrating function callback\n");
    /* register our callback function */
    register_callback(ptr_my_callback);                          
    printf("back inside main program\n");
    return 0;
}

/* reg_callback.h */
typedef void (*callback)(void);
void register_callback(callback ptr_reg_callback);


/* reg_callback.c */
#include<stdio.h>
#include"reg_callback.h"

/* registration goes here */
void register_callback(callback ptr_reg_callback)
{
    printf("inside register_callback\n");
    /* calling our callback function my_callback */
    (*ptr_reg_callback)();                               
}

If we run this program, the output will be

This is a program demonstrating function callback inside register_callback inside my_callback back inside main program

The higher layer function calls a lower layer function as a normal call and the callback mechanism allows the lower layer function to call the higher layer function through a pointer to a callback function.

Callback in Java Using Interface

Java does not have the concept of function pointer It implements Callback mechanism through its Interface mechanism Here instead of a function pointer, we declare an Interface having a method which will be called when the callee finishes its task

Let me demonstrate it through an example:

The Callback Interface

public interface Callback
{
    public void notify(Result result);
}

The Caller or the Higher Level Class

public Class Caller implements Callback
{
Callee ce = new Callee(this); //pass self to the callee

//Other functionality
//Call the Asynctask
ce.doAsynctask();

public void notify(Result result){
//Got the result after the callee has finished the task
//Can do whatever i want with the result
}
}

The Callee or the lower layer function

public Class Callee {
Callback cb;
Callee(Callback cb){
this.cb = cb;
}

doAsynctask(){
//do the long running task
//get the result
cb.notify(result);//after the task is completed, notify the caller
}
}

Callback Using EventListener pattern

  • List item

This pattern is used to notify 0 to n numbers of Observers/Listeners that a particular task has finished

  • List item

The difference between Callback mechanism and EventListener/Observer mechanism is that in callback, the callee notifies the single caller, whereas in Eventlisener/Observer, the callee can notify anyone who is interested in that event (the notification may go to some other parts of the application which has not triggered the task)

Let me explain it through an example.

The Event Interface

public interface Events {

public void clickEvent();
public void longClickEvent();
}

Class Widget

package com.som_itsolutions.training.java.exampleeventlistener;

import java.util.ArrayList;
import java.util.Iterator;

public class Widget implements Events{

    ArrayList<OnClickEventListener> mClickEventListener = new ArrayList<OnClickEventListener>(); 
    ArrayList<OnLongClickEventListener> mLongClickEventListener = new ArrayList<OnLongClickEventListener>();

    @Override
    public void clickEvent() {
        // TODO Auto-generated method stub
        Iterator<OnClickEventListener> it = mClickEventListener.iterator();
                while(it.hasNext()){
                    OnClickEventListener li = it.next();
                    li.onClick(this);
                }   
    }
    @Override
    public void longClickEvent() {
        // TODO Auto-generated method stub
        Iterator<OnLongClickEventListener> it = mLongClickEventListener.iterator();
        while(it.hasNext()){
            OnLongClickEventListener li = it.next();
            li.onLongClick(this);
        }

    }

    public interface OnClickEventListener
    {
        public void onClick (Widget source);
    }

    public interface OnLongClickEventListener
    {
        public void onLongClick (Widget source);
    }

    public void setOnClickEventListner(OnClickEventListener li){
        mClickEventListener.add(li);
    }
    public void setOnLongClickEventListner(OnLongClickEventListener li){
        mLongClickEventListener.add(li);
    }
}

Class Button

public class Button extends Widget{
private String mButtonText;
public Button (){
} 
public String getButtonText() {
return mButtonText;
}
public void setButtonText(String buttonText) {
this.mButtonText = buttonText;
}
}

Class Checkbox

public class CheckBox extends Widget{
private boolean checked;
public CheckBox() {
checked = false;
}
public boolean isChecked(){
return (checked == true);
}
public void setCheck(boolean checked){
this.checked = checked;
}
}

Activity Class

package com.som_itsolutions.training.java.exampleeventlistener;

public class Activity implements Widget.OnClickEventListener
{
    public Button mButton;
    public CheckBox mCheckBox;
    private static Activity mActivityHandler;
    public static Activity getActivityHandle(){
        return mActivityHandler;
    }
    public Activity ()
    {
        mActivityHandler = this;
        mButton = new Button();
        mButton.setOnClickEventListner(this);
        mCheckBox = new CheckBox();
        mCheckBox.setOnClickEventListner(this);
        } 
    public void onClick (Widget source)
    {
        if(source == mButton){
            mButton.setButtonText("Thank you for clicking me...");
            System.out.println(((Button) mButton).getButtonText());
        }
        if(source == mCheckBox){
            if(mCheckBox.isChecked()==false){
                mCheckBox.setCheck(true);
                System.out.println("The checkbox is checked...");
            }
            else{
                mCheckBox.setCheck(false);
                System.out.println("The checkbox is not checked...");
            }       
        }
    }
    public void doSomeWork(Widget source){
        source.clickEvent();
    }   
}

Other Class

public class OtherClass implements Widget.OnClickEventListener{
Button mButton;
public OtherClass(){
mButton = Activity.getActivityHandle().mButton;
mButton.setOnClickEventListner(this);//interested in the click event                        //of the button
}
@Override
public void onClick(Widget source) {
if(source == mButton){
System.out.println("Other Class has also received the event notification...");
}
}

Main Class

public class Main {
public static void main(String[] args) {
// TODO Auto-generated method stub
Activity a = new Activity();
OtherClass o = new OtherClass();
a.doSomeWork(a.mButton);
a.doSomeWork(a.mCheckBox);
}
}

As you can see from the above code, that we have an interface called events which basically lists all the events that may happen for our application. The Widget class is the base class for all the UI components like Button, Checkbox. These UI components are the objects that actually receive the events from the framework code. Widget class implements the Events interface and also it has two nested interfaces namely OnClickEventListener & OnLongClickEventListener

These two interfaces are responsible for listening to events that may occur on the Widget derived UI components like Button or Checkbox. So if we compare this example with the earlier Callback example using Java Interface, these two interfaces work as the Callback interface. So the higher level code (Here Activity) implements these two interfaces. And whenever an event occurs to a widget, the higher level code (or the method of these interfaces implemented in the higher level code, which is here Activity) will be called.

Now let me discuss the basic difference between Callback and Eventlistener pattern. As we have mentioned that using Callback, the Callee can notify only a single Caller. But in the case of EventListener pattern, any other part or class of the Application can register for the events that may occur on the Button or Checkbox. The example of this kind of class is the OtherClass. If you see the code of the OtherClass, you will find that it has registered itself as a listener to the ClickEvent that may occur in the Button defined in the Activity. Interesting part is that, besides the Activity ( the Caller), this OtherClass will also be notified whenever the click event occurs on the Button.

Marinamarinade answered 16/5, 2017 at 15:50 Comment(1)
Please avoid link only answers. Answers that are "barely more than a link to an external site” may be deleted.Forestay
B
4

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).

Base answered 24/5, 2018 at 10:14 Comment(1)
This answer seems like one of the most accurate answers based on my understanding.Discomfortable
E
4

A callback is an idea of passing a function as a parameter to another function and have this one invoked once the process has completed.

If you get the concept of callback through awesome answers above, I recommend you should learn the background of its idea.

"What made them(Computer-Scientists) develop callback?" You might learn a problem, which is blocking.(especially blocking UI) And callback is not the only solution to it. There are a lot of other solutions(ex: Thread, Futures, Promises...).

Elman answered 26/4, 2019 at 3:20 Comment(0)
H
2

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.

Herrera answered 5/5, 2009 at 10:34 Comment(0)
R
2

The other answers sum up the crux of the question "What is a callback?"

It's just a function that calls another function when something is completed.

What got me was the examples, "You did this now do that." Like WHY would I use it like that when I can just call a method or a function myself?

So here's a quick, real world example that hopefully makes it "click" for someone.

Ultra pseudocode

First the core issue you'll run into....

Multithreaded Method(Some arguments)
  {
    Do fancy multithreaded stuff....
  }

Main()
 {
   Some stuff I wanna do = some tasks
   Multhreaded Method(Some stuff I wanna do)
 }

If you run that without any callback your program will look like it just exits. Because the "Fancy multithreaded stuff" is running on another process.

So you scratch your head and think "Well hell, How do I know when it's done??"

BOOM... CALLBACK

IsItDone = false

Callback()
{
  print("Hey, I'm done")
  IsItDone = true
}
  
Multithreaded Method(Some arguments, Function callback)
  {
    Do fancy multithreaded stuff....
  }

Main()
 {
   Some stuff I wanna do = some tasks
   Multhreaded Method(Some stuff I wanna do,Callback)

   while(!IsItDone)
     Wait a bit
 }

This is 100% not the best way to implement it, I just wanted to give a clear example.

So this isn't the bare "What is a callback?" It's "What is a callback, and what does it do that benefits me???"

Romanist answered 25/9, 2022 at 19:17 Comment(0)
D
1

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.

Duncan answered 26/4, 2015 at 20:21 Comment(1)
A callback function is not itself a higher-order function. It is passed to a higher-order function.Closed
S
1

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.

Springs answered 8/1, 2018 at 12:56 Comment(2)
Welcome to Stack Overflow! Before answering a question, always read the existing answers. This answer has already been provided. Instead of repeating the answer, vote up the existing answer. Some guidelines for writing good answers can be found here.Keynes
Well, it's true most of the time, but sometimes, you pass a callback function by setting a property of object instance. ex: myButton.Click += (sender, args) => SomeFunction(); (in c#)Base
O
0

A callback is a function that is called back if a condition has been fulfilled.

Think of an audition where you are called back if you get selected. Likewise, callbacks are called if the particular condition is met.

Oubre answered 9/3 at 14:24 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.