Callback functions, Event loop & JS Engine in Javascript.
Hello everyone, this blog will be divided in to three parts as the title mentioned.
- Callback functions
- Event Loop
- JS Engine
1. Callback functions
In simple words , callback function are those functions which are passed as arguments into other functions.
function x(y){
console.log("x")
y();
}
x(function y(){
console.log("y")
})
// Output
x
y
function y is callback function. function x has responsibility of calling the y function.
This is all single threaded. The entire code is running on one thread i.e Main thread. What if we add setTimeout() above function x and attach a timer of 5000 ms(5 sec) to it ?? Lets do it -
setTimeout(function() {
console.log("timer");
},5000)
function x(y){
console.log("x")
y();
}
x(function y(){
console.log("y")
})
// Output
x
y
timer
Javascript has only one call stack. Whatever is executed on your page is executed through call stack only. So, any of function x , y and setTimeout is executed through call stack. If any operation blocks this calls stack that is known as Blocking the Main Thread. If function x has heavy operation which takes 20 sec to complete so the call stack will blocked and any other function will not be executed for 20 sec.
In other words, we should always use async operations for things which takes time just like setTimeout(). Using callback and web api(setTimeout()) we can achieve the asynchronous operations.
CallBack functions in Event Listeners
//2. Call back in event listeners
document.getElementById("clickme")
.addEventListener("click",function xyz(){
console.log("clicked")
})
// function xyz is callback function and xyz will be added in the call stack when event listener is called
Now, what if we want to count how many times a button was clicked ?? A simple solution would be declare a global variable and add the value of the variable by 1 every time button is clicked. For reference -
let count = 0
document.getElementById("clickme")
.addEventListener("click",function xyz(){
console.log("clicked", ++count)
})
// Output
clicked 1
clicked 2
...
But wait , using a global variable is best solution ??
No , not an optimal solution because count (variable) can be modified by other functions and pieces of code as well. So what we do now ?
We have to restrict the access of variable i.e data hiding. We can achieve data hiding using CLOSURES