What is the meaning of callback function in javascript.
A callback function is a function passed into another function as an argument, which is then invoked inside the outer function to complete some kind of routine or action.
A callback's primary purpose is to execute code in response to an event. These events might be user-initiated, such as mouse clicks or typing. With a callback, you may instruct your application to "execute this code every time the user clicks a key on the keyboard." button.
"I will call back later!" A callback is a function passed as an argument to another function. This technique allows a function to call another function. A callback function can run after another function has finished.
The main difference between a normal function and a callback function can be summarized as follows: A normal function is called directly, while a callback function is initially only defined. The function is only called and executed once a specific event has occurred.
JavaScript's "callback" is function object that can be passed to some other function (like a function pointer or a delegate function), and then called when the function completes, or when there is a need to do so. For example, you can have one main function to which you can pass a function that it will call...
Main function can look like this:
function mainFunc(callBack)
{
alert("After you click ok, I'll call your callBack");
//Now lets call the CallBack function
callBack();
}
You will call it like this:
mainFunc(function(){alert("LALALALALALA ITS CALLBACK!");}
Or:
function thisIsCallback()
{
alert("LALALALALALA ITS CALLBACK!");
}
mainFunc(thisIsCallback);
This is extensively used in javascript libraries. For example jQuery's animation() function can be passed a function like this to be called when the animation ends.
Passing callback function to some other function doesn't guarantee that it will be called. Executing a callback call (calBack()
) totally depends on that function's implementation.
Even the name "call-back" is self-explanatory... =)
It's just a name for a function that should be called back after something.
It's often used with XMLHttpRequest:
var x = new XMLHttpRequest();
x.onreadystatechange = function(){
if(x.readyState == 4){
callbackfunction(x.responseText);
}
}
x.open('get', 'http://example.com/', true);
x.send(null);
callbackfunction
is just a plain function, in this case:
function callbackfunction(text){
alert("I received: " + text);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With