Is just a function that executes after one other function that calls it, finishes?
Please I know (almost) nothing about programming, and I find it quite hard to find
Imagine you have some complex piece of code and right in the middle of it, you must do "something". The problem: You have no idea what "something" might be since that depends on how the code is used. Callback to the rescue.
Instead of having code, you just put a callback there. The user can supply her own piece of code and it will be executed just at the right time to do some critical thing. Example: jQuery.filter(callback)
.
jQuery (which you should have a look at) will call callback
for each element in a list. The callback function can then examine the element and return true
if it matches some criteria.
This way, we have the best of two worlds: The smart people at jQuery create the filter and you say what exactly to look for.
Trying to get a more general and simple example, I figured out the following, and with arguments to performe a calculation with two numbers: x and y.
function doMath (x,y,myMath) {return myMath(x,y);}
function mult (a,b){return a*b;}
function sum (a,b){return a+b;}
alert(doMath(2,2,sum))
where myMath is the callback function. I can replace it for any function I want.
A callback function is a function that is automatically called when another process ends. They are very usefull in asyncronous process, like get a page.
EDIT
Example: You want to get make a ajax call (get a page for example). And you want to run some function when donwload finishes.
With jquery, you can use this:
$.get('PageIWant.html', myCallBack);
function myCallBack (data){
alert('I have got the page!');
}
A callback function is "A reference to executable code, or a piece of executable code, that is passed as an argument to other code."
Here is a good article to help understand what is a "callback" function.
A callback is simply a function you specify that is called not immediately but usually after some event. This could be something like an ajax request, you would specify a callback that is invoked only when the ajax request is successfully completed and doesn't error out. Another example would be a callback for when the DOM in a web page is ready, or the window loads.
Code like this
var result = db.query('select * from T'); //use result - Standard function
your software is doing nothing and you are just waiting for the database to respond. this somehow either blocks the entire process or implies multiple execution stacks. But a line of code like this
db.query('select * from T',function(result){
//use result - Callback function
});
allow the program to return to the event loop immediately.
In this execution, server makes that request and continue doing other things, when the request comes back(after millions of clock cycles), you can execute the callback, all you need is the pointer to the callback.