A callback is typically the address of a function or method or lambda expression provided when invoking an API. When an action completes, the expression is executed or "called back". Asynchronous APIs use callbacks to notify the calling function when an operation is complete. Use this tag for questions involving asynchronous APIs requiring a call back expression. Use the tag event-handling for questions on registering or subscribing for events, e.g. GUI.
A callback argument is the address of a function or method or lambda expression which is executed when the function that receives the callback argument completes some action.
A callback argument is normally used with asynchronous functions or APIs in which a function is called in order to start some action which may take a while to complete. Examples of this kind of an action are:
- writing to a disk file or other storage,
- accessing a REST web service to request data, and
- displaying a dialog which displays information which must be collected at the time the dialog is displayed such as a print dialog which shows which printers are available on the local network.
In the above examples, the action requested may take several milliseconds to several seconds from when it is initiated to when it completes. The use of a callback argument allows the function to be called in order to start the action knowing that when the action is complete the call back will be invoked for any final functionality needed by the caller once the action is complete.
These other actions may be happening in some other thread or some other process or some other device however the API provides some guarantee that when the action completes or it times out, the call back will be called to let you know the final results of the action.
See also:
- Stack Overflow: What is the difference between synchronous and asynchronous programming (in node.js)
- A guide to asynchronous programming in Python with asyncio
- Stack Overflow: Asynchronous vs Multithreading - Is there a difference?
The primary difference between an event handler and a callback is that a callback is typically a one shot deal in which an action is started, the action completes, the callback is invoked.[citation needed]
An event handler is a function or method or lambda expression which is provided as part of subscribing to one or more events. The idea of an event handler is that it may be called repeatedly as the events happen and the event handler may be one of several event handlers chained together and all subscribing to the same event. An example would be an event handler for button events or mouse events in a GUI.