Reputation: 9920
I am confused about the time when a callback function is executed. It is passed as an argument when calling some XYZ function. Shouldn't it get executed when the call to XYZ function is made? or would it get executed when some 'IF' condition is met inside the XYZ function?
thanks in advance
Upvotes: 0
Views: 2230
Reputation: 38213
A callback function is a function that occurs after some event has occurred. The reference in memory to the callback function is usually passed to another function. This allows the other function to execute the callback when it has completed its duties by using the language-specific syntax for executing a function.
It could get executed immediately when the other function is called, or when some 'IF' condition is made. The time when the callback is executed is determined by the code inside the function that you are passing the callback to.
Here's psuedocode for an example when you would execute a callback, if you successfully printed out a string. This assumes that the print()
function returns TRUE if it successfully prints the string and FALSE if it does not succeed:
function XYZ(string,referenceToCallbackFunction)
{
boolean printSuccess = print(string); // returns TRUE on success
if(printSuccess == TRUE)
{
execute(referenceToCallbackFunction); // Here we execute or "call" the callback
}
else
{
/* we didn't execute the callback
because printing the string was not successful
*/
}
}
Here's the callback function definition's psuedocode:
function callback()
{
print('Hurray! Printing succeeded in the other function.');
}
Here's the function call to the other function, where the reference to the callback is passed:
referenceToCallbackFunction = callback; // Notice the lack of () means don't execute the function
XYZ("Let's see if this prints out",referenceToCallbackFunction); // This executes XYZ and passes the callback reference as a parameter so that XYZ can execute it at a later time
The output would be:
Let's see if this prints out
Hurray! Printing succeeded in the other function.
Upvotes: 1