A callback function is a function that is passed to
another function as a parameter.
A callback function is also known as a higher-order
function.
A callback function is essentially a pattern (an
established solution to a common problem), and therefore, the use of a callback
function is also known as a callback pattern.
A callback function can be a Named function or an
anonymous function.
Example1
|
Example2
|
$("#btn_1").click(function() {
alert("Button 1 Clicked");
});
|
setTimeout(function () {
alert('hello');
}, 1000);
|
In the above examples, the click method's parameter is
a function, not a variable, this is a callback function.
And the click method will call (or execute) the
callback function that we passed to it. This is a typical use of callback functions
in JavaScript, and indeed it is widely used in jQuery.
When we pass a callback function as an argument to
another function, we are only passing the function definition, we are not
executing the function in the parameter
Callback function is not executed immediately. It
is “called back” (hence the name) at some specified point inside the containing
function’s body.
Uses:
1) jQuery uses callback functions extensively