newbie approach: what is a javascript callback function?
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 a proper newbie answer or explanation about what does this means.
Can I request a try from stackoverflow guru开发者_运维知识库s?
In general, a callback function is used once another function you have called finishes (just like you stated in your question). A good example of this is AJAX requests: most libraries have a function that allows you to send a request to the server in the background without refreshing the page (this uses AJAX). You generally provide two callback functions to this AJAX function: a success function, and a failure function.
If this request succeeds, it calls the success function so that your code can do what it needs; for instance, it might refresh part of the page, do some sort of animation, or alert the user that their information was saved. On the other hand, if it failed, the callback function would probably alert the user that their data was not saved and that they should try again.
Callback functions allow library developers to create very generic code that others can use and then customize to their needs.
Below is some jQuery code to show you the example above (this code won't work as the URL doesn't exist):
jQuery.ajax(
url: '/mywebsite/somepage.php',
success: function itWorked(returnedData) {
// This is the success function and will be called only if the ajax call
// completes succesfully
alert('Yay it worked! ' + returnedData);
},
error: function itFailed(originalRequest, textStatus, errorThrown) {
// This is the error function and will only be called if the ajax call
// has an error
alert('It failed! ' + textStatus + '. ' + errorThrown);
}
);
EDIT: At the beginning, I said, "In general...". In reality, callbacks are used for much more than just when a function finishes. Like stated in other answers, it can be used anywhere inside of a function: beginning, middle, end. The basic idea is that the developer of the code may not know how YOU are going to use HIS code. So, he makes it very generic and gives you the ability to do whatever you need with the data.
A good example of this is the jQuery.each method which allows you to pass in a callback that will be executed on each of the elements in the "array" (I say array because it can actually iterate over many things which may or may not be actual arrays).
<a href='someurl.html' class='special_link'>Some URL</a>
<a href='anotherurl.html' class='special_link'>Another URL</a>
<a href='onelasturl.html' class='special_link'>One Last URL</a>
// The following code says: execute the myEachCallbackFunction on every link
// that has a class of 'special_link'
$('a.special_link').each(function myEachCallbackFunction(i) {
// The link variable will contain the object that is currently
// being iterated over. So, the first time through, it will hold
// the 'someurl.html' link, the second time it will hold the
// 'anotherurl.html' link, and the last time it will hold the
// 'onelasturl.html' link
var link = $(this);
// Change the background color of each link to be red
link.css('background-color', 'red');
});
So, we can see from this example that the developers of jQuery implemented the .each method and allow us to do whatever we want to to each link that it is called upon.
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.
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.
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!');
}
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.
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.
精彩评论