James Anderson's answer is the most detailed.
Expanding on his answer;
Callback refers to any code, that is passed as an argument to a method, intended to be called later asynchronously. However, a callback doesnt define how the process of callback itself should be implemented. This is where the classification of callbacks begin.
Traditionally, a callback process would look :
- the developer defines a callback and passes it onto a library defined function (one which knows what to do with the callback so that the calling process or detecting process can call it) for e.g. in node,
var server = require('http').createServer(function(req, res){/* your code */});
the createServer is the library defined function which makes sure the detecting process gets to call the correct callback, which in this case is function(req, res){/* your code */}
- during runtime, the detecting process receives the direct location of callback (because the library defined function did it for you) and calls it. This would mean 2 things:
- the developers of the library would always need to know how to deal with different detecting processes as each may have a different way of calling back
- and if the callback needs to be called multiple times, it might task the detecting process. For e.g. if the detecting process is a GUI process, then you would want the GUI thread to run with as much less task as possible, for a smooth GUI experience.
Thus resulted the need for implementing a mechanism of callback, which solved these 2 issues:
- an external process that would define a concurrent point for the library function to register callbacks and for the detecting process to notify as to when these registered callbacks need to be called.
- This meant the developers of both these processes can now work independently of each other, without really knowing each other's ways.
- This external process came to be known as event loop(in node, for e.g.). The term 'event' is simply the process of notifying the event loop by the detecting process and the registered callback came to be known as the event handler.
- the external process(or the event loop) queued the events and executed them, thus taking the load off the detecting process which could now resume to whatever it was doing best.
Thus for events that occurred multiple times, the event loop or the event handlers became the way of implementing callbacks, while the original callbacks are still preferred for one-off events as you are not really tasking the detecting process and dont need to have the event loop for just one event as its not efficient.
- The node js code above is a one-off event (as the connection to the server for a client is a one-off event while there can be many responses which are implemented as event handlers) and is an example of simple callback.