What Is a Callback

How to explain callbacks in plain english? How are they different from calling one function from another function?

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.

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]

Javascript: what is a callback?

In general, the call to the callback is not at the end of the function, but rather after you have done the important things.

So if I understand your question, the doHomework-function should start doing homework (which takes time, in this case 500ms), and then the homework is finished. So the important things in your case is the console.log('Starting my ${subject} homework.'); which "takes 500ms" (since this is the time you need to do the homework).

Therefore, you should put the call to the callback right after console.log('Starting my ${subject} homework.');, i.e.

function doHomework(subject, callback) {

setTimeout(function(){
console.log(`Starting my ${subject} homework.`);
callback();
}, 500);
}

doHomework('math', function() {
console.log('Finished my homework');
});

What is a callback?

In computer programming, a callback is executable code that is passed as an argument to other code.

—Wikipedia: Callback (computer science)

C# has delegates for that purpose. They are heavily used with events, as an event can automatically invoke a number of attached delegates (event handlers).

What is a callback in java

Maybe an example would help.

Your app wants to download a file from some remote computer and then write to to a local disk. The remote computer is the other side of a dial-up modem and a satellite link. The latency and transfer time will be huge and you have other things to do. So, you have a function/method that will write a buffer to disk. You pass a pointer to this method to your network API, together with the remote URI and other stuff. This network call returns 'immediately' and you can do your other stuff. 30 seconds later, the first buffer from the remote computer arrives at the network layer. The network layer then calls the function that you passed during the setup and so the buffer gets written to disk - the network layer has 'called back'. Note that, in this example, the callback would happen on a network layer thread than the originating thread, but that does not matter - the buffer still gets written to the disk.

what is a callback function in comparison to a standard function

From Wikipedia:

A callback is a piece of executable code that is passed as an argument
to other code, which is expected to call back (execute) the argument
at some convenient time. The invocation may be immediate as in a
synAhronous callback or it might happen at later time, as in an
asynchronous callback. In all cases, the intention is to specify a
function or subroutine as an entity that is, depending on the
language, more or less similar to a variable.

Basically a callback function is a function that you pass as a parameter to some other event or function. It allows the code to execute the callback-function at a time of its choosing with parameters of its choosing.

For example:

function my_callback(evt){alert("Button clicked!");}

$('#button').click(my_callback)

We pass the function my_callback to the event code, which can then pass its own event object to the function when jQuery decides it is appropriate

What is a callback in C and how are they implemented?

There is no "callback" in C - not more than any other generic programming concept.

They're implemented using function pointers. Here's an example:

void populate_array(int *array, size_t arraySize, int (*getNextValue)(void))
{
for (size_t i=0; i<arraySize; i++)
array[i] = getNextValue();
}

int getNextRandomValue(void)
{
return rand();
}

int main(void)
{
int myarray[10];
populate_array(myarray, 10, getNextRandomValue);
...
}

Here, the populate_array function takes a function pointer as its third parameter, and calls it to get the values to populate the array with. We've written the callback getNextRandomValue, which returns a random-ish value, and passed a pointer to it to populate_array. populate_array will call our callback function 10 times and assign the returned values to the elements in the given array.

How can I provide a callback to an API?

A callback is a function provided by the consumer of an API that the API can then turn around and invoke (calling you back). If I setup a Dr.'s appointment, I can give them my phone number, so they can call me the day before to confirm the appointment. A callback is like that, except instead of just being a phone number, it can be arbitrary instructions like "send me an email at this address, and also call my secretary and have her put it in my calendar.

Callbacks are often used in situations where an action is asynchronous. If you need to call a function, and immediately continue working, you can't sit there wait for its return value to let you know what happened, so you provide a callback. When the function is done completely its asynchronous work it will then invoke your callback with some predetermined arguments (usually some you supply, and some about the status and result of the asynchronous action you requested).

If the Dr. is out of the office, or they are still working on the schedule, rather than having me wait on hold until he gets back, which could be several hours, we hang up, and once the appointment has been scheduled, they call me.

In this specific case, the documented method will compute the result, put it together with any callbackargs specified, and call callback, passing it those values as the arguments.

What is a callback? What is it for and how is it implemented in for example C++

I am familiar with some Java and C#

A callback is an event or delegate in those languages - a way to get your code run by somebody else's code in it's context. Hence, the term "callback":

  1. You call some other piece of code
  2. It runs, perhaps calculating an intermediate value
  3. It calls back into your code, perhaps giving you that intermediate value
  4. It continues running, eventually passing control back to you by completing

A canonical example is a sort routine with a user defined comparison function (the callback). Given a sort routine such as:

void Sort(void* values, int length, int valueSize, 
int (*compare)(const void*, const void*)
{
for (int i = 0; i < length; i = i + 2) {
// call the callback to determine order
int isHigher = compare(values[i], values[i + 1]);
/* Sort */
}
}

(The specifics of how the sort is performed isn't important - just focus on the fact that any sorting algorithm needs to compare 2 values and determine which is higher.)

So, now we can define some comparison functions:

int CompareInts(const void* o, const void* p) {
int* a = (int*) o;
int* b = (int*) p;

if (a == b) return 0;
return (a < b) ? -1 : 1;
}

int ComparePersons(const void* o, const void* p) {
Person* a = (Person*) o;
Person* b = (Person*) p;

if (a == b) return 0;
return (a->Value() < b=>Value()) ? -1 : 1;
}

And reuse the same sort function with them:

int intValues[10];
Person personValues[10];

Sort(intValues, 10, sizeof(intVaues[0]), CompareInts);
Sort(personValues, 10, sizeof(personVaues[0]), ComparePersons);

Things get a bit more complicated if you're using member functions, as you have to manage the this pointer - but the concept is the same. As with most things, it's easier to explain them in C first. ;)



Related Topics



Leave a reply



Submit