Callback Functions
Written By: Avinash Malhotra
Updated on
JavaScript Callback Function
A function that is passed as an argument to another function is known as callback function. This means, callback functions are just any JavaScript function, but that can be used as an argument to another function.
Callback Functions are high order functions. A high order functions in javascript includes callback functions and function that returns a function.
Callback Function Example
hi
function main(x){
x();
}
function callback(){
console.log("hi");
}
main(callback);
In the above example, main is a function with parameter x. Inside main function, we are calling x
. This means x should be a function, not any other datatype. Argument of main function is callback
. The above example is synchronous callback as the code execute immediately.
Synchronous Callback
Synchronous callback is a callback where code execute immediately, i.e. synchronously. All the code in main thread will be executed line by line. See example
Synchronous Callback example
Show is at 9
Show Ends
done
function showTime(x,done){
console.log(" Show is at ", x);
done();
}
function showEnd(){
console.log("Show Ends")
}
showTime(9,showEnd);
console.log('done')
The above code will execute line by line. That's why, the last line, i.e. console.log("done");
executes in the end. That's why, it is called synchronous callback.
callback in array
To filter or sort array, use Arrow Function as callback. Array callback functions are also synchronous by default.
[2,4,8]
done
const num=[1,2,4,8,11];
const even=num.filter(i=>i%2==0);
console.log(even);
console.log('done')
callback function used in arrays are also synchronous.
Asynchronous Callback
Asynchronous callback is a callback where code within callback function is executed after main thread is completed. Event Loop handle all the asynchronous operations in JavaScript. For asynchronous callback, we can use any one of below techniques in javascript.
Asynchronous techniques in javascript
- setTimeout / setInterval
- events
- ajax/fetch
- Promises
- async await
Event Loop
Event Loop is the runtime model on which javascript is based. By default frontend javascript is synchronous. But using Event Loop, we can run asynchronous programs in javascript.
Asynchronous callback is one of the main reason behind performance of JavaScript. The main thread executes synchronous code first and the long waiting tasks are kept inside asynchronous functions using Event Loop, like setTimeout timing function with callback. All non blocking methods are executed using Event Loop which use Asynchronous callback in JavaScript and Node JS.
To avoid callback hell, we will use JavaScript promises for efficient asynchronous operations.
How event loop works?
The Call Stack executes synchronous code first time when webpage is loaded. During this time, we can see loading animation spinner in title for chrome/edge, progress bar in safari and linear loading animation in firefox. Once the animation is done, this means the document is ready and window is loaded including images, videos, ads and iframes. JavaScript load all asynchronous callbacks in call stack, but its waiting for the event or timer.
Once an event is triggered, like we click on button, the event loop pass the callback function to Que Stack. Que Stack wait for the completion of previous task on call stack. Once the call stack is free, Que Stack will pass the callback to Call Stack and the task will be performed asynchronous.
Many Programming languages follow this technique like Java. Even NgInx server use same technique to handle much more traffic on web server with less latency, more performance and efficiency.
Synchronous Vs Asynchronous
Synchronous code
1
2
3
console.log(1);
setTimeout(console.log(2));
console.log(3);
Asynchronous code
1
3
2
console.log(1);
setTimeout(i=>console.log(2));
console.log(3);
Asynchronous using promise
Javascript Promises are meant for asynchronous programming. We will learn Promises in detail in upcoming sessions.
2
1
const p=Promise.resolve(1);
p.then(i=>console.log(i));
console.log(2);
Parameters in callback function
To pass parameters in callback function, we need to parameter in parent function first and then pass it to callback function. See example
Class starts at 10
Projector running using hdmi
function startClass(x,y,z){
console.log(" Class starts at", x);
y(z);
}
function onProjector(x){
console.log("Projector running using ", x)
}
startClass(10,onProjector,"hdmi");
In the above example, startClass is the main function and onProjector is the callback. First parameter is parameter of startClass, second parameter is callback function and third parameter is parameter of callback function.
In ES6, we can use JavaScript Promise to handle long and nested Asynchronous operations.