What is Callback functions
As we know in javascript functions are objects , that means we can pass them as arguments to other functions and call them inside the outter function
Lets see a small example
When you pass swallow() function as parameter reference to chew function is likely to execute swallow() at some point . In that case swallow() is called callback function
function chew(callback) {
//Chew the food
callback();
}
function swallow() {
// ...Swallow the food
}
chew(swallow);
Here its important to notice that swallow is passed as an argument to chew() without parenthesis , because parentheses execute a function where in callback scenario we want to pass only a reference to the function and let the chew function to execute it
Refactoring Normal Functions into Callback
Imagine you have a general-purpose function that does some complicated work and find the open processes and returns a big dataset as a result . This function could be called findProcesses() . Imagine also we need to kill each process individually in different method (kill())
var findProcesses = function () {
var i = 1000, // Big loop
processes = [], //empty array to store all the processes
found; //the next proceess is found
while(i) {
i -= 1;
processes.push(found)
}
return processes;
};
//function that hide the process from DOM
var kill = function (processes) {
var i = 0 , max=processes.length;
for (;i<max; i +=1) {
processes[i].style.display = "none";
}
}
//executing
kill(findProcesses());
Note that in the above example the implementation is inefficient because kill has to loop again through they array of processes returned by findProcesses(). It would be better and more efficient if we could avoid this loop and kill the process as soon as we selecting them in findProcesses.
Lets do it by using callback ...
//findProcesses function supporting callback
var findProcesses = function (callback) {
var i = 1000,
processes = [],
found;
//check if callback is callable
if (typeof callback !== "function") {
callback = false;
}
while (i) {
i = -1;
//complex logic
//call callback
if(callback) {
callback(found)
}
processes.push(found);
}
return processes;
}
//callback function
var kill = function(process) {
process.style.display = "none";
}
//find process and kill them as you go
findProcesses(kill)
The above implementation with callback is straightforward and more efficient because it doesn't need repeat the loop process second time in kill() method
Wrap up
Now you are loaded with a extra gun on your pocket, take the time to use it in your codebase to make your code faster and more efficient
Top comments (0)