Function vs Callback Function
Callbacks are just functions, but instead of being called by the programmer explicitly, they are called by the computer in specific circumstances.
function callbackFunction() {
//...
}
function executeCallback( callbackParm ) {
//...
callbackParm();
//...
}
executeCallback(callbackFunction);
executeCallback( callbackFunction );
Notice there are no parentheses, because we are not calling the function, we are passing it because we want the computer to call it.
Any function can become a callback function if it is passed into another function as a parameter for later use.
Simple callback example
// Normal function used as callback
function sayHello() {
console.log('Hello');
}
// Function will invoke callback function
function executeCalleback( callback ){
callback();
}
// Run function
executeCallback(sayHello);
// output: 'Hello'
Other examples
onClick(showHint);
everySecond(tickClock);
readFile("storyFile.txt", printStory);
showHint
, tickClock
, and printStory
are all examples of callback functions passed as arguments to functions.
Callback Use Cases
- Timers, one-offs and repeating ones (e.g. screen clocks).
- Triggered by a user interaction (e.g. interaction events).
- Loading data from a server (e.g. using AJAX).
- Opening and complete reading a file (e.g. in Node.js).
- And many more…
Synchronous & Asynchronous Programming
Synchronous Programming with Normal Functions – When you call or invoke a function within your code block, you’re asking for the function’s code to be executed immediately.
Asynchronous Programming – When you use the function as a callback, it gets executed or invoked when it’s supposed to sometime in the future!