A callback function (in JavaScript) is a function, passed as an argument, that is invoked if a certain event is picked up on, or after a predefined period of time. jQuery callbacks are exactly the same as JavaScript callbacks, except that jQuery invokes the callback in a set context that sometimes differs from the one in vanillaJS.
In programming, a callback is a piece of executable code that is registered to be invoked as a response to certain events. This can be anything ranging from an interupt, a certain system signal being received to the more high-level user events that are used in jQuery.
jQuery callbacks are exactly the same as JavaScript callbacks, apart from one thing: JavaScript invokes callback functions either in the global (window
) context, or the context of a particular DOM element. The latter being relevant to callbacks (often referred to as handlers) passed to the addEventListener
method.
When using techniques like event delegation, a regular JavaScript handler will invoke the callback in the context of the DOM element to which the listener is attached. jQuery will invoke the callback in the context of the event's target.
An example of this distinction:
$('body').on('click', 'a', function()
{
console.log(this);//refers to the link that was clicked
});
document.body.addEventListener('click', function(e)
{
var target = e.target || e.srcElement;
if (target.tagName.toLowerCase() === 'a')
{
console.log(this);//logs body, that's where the listener was bound
console.log(target);//logs the clicked link
}
}, false);
Other examples of callbacks are functions passed to setTimeout
or setInterval
. These functions are put in a queue, waiting for the pre-set interval to pass, and are then invoked by the JS engine, if, and only if, the JS engine is free at that time.
The programmer has no real control over the order in which the queue is processed, in case several event handlers are queued, it could be that first all the handlers are invoked, and then the timeout callback gets its turn, or the other way around.
jQuery let's programmers create their own queue, using $.queue
, which they can control.