Callback Function
Functions are first-class citizens, meaning take a function and pass into another function.It provides access to the entire asynchronous world in a synchronous world.
function x(y){
}
x(function y(){
});
Take a function y and pass it into another function x. Here, y is a callback function. This allows function x to call function y.
setTimeout(function () {
console.log("Timer");
}, 8000)
The function passed as the first parameter to setTimeout is the callback function, and the second parameter is the timer.
JavaScript is a synchronous and single-threaded language. However, with callbacks, we can perform asynchronous operations in JavaScript.
setTimeout(function () {
console.log("timer");
}, 6000);
function x(y) {
console.log("x");
y();
}
x(function y() {
console.log("y");
});
Look at the above code. Initially, x and y are present in the call stack, and then the call stack becomes empty. setTimeout will take this callback function and store it in a separate space, attaching a timer to it(Eg:6 seconds). After 6 seconds, the timer will be added to the call stack.
If x() takes 20 seconds to run, JavaScript must wait for it to finish. JavaScript has only one call stack, which is also referred to as the main thread.
Everything is executed through the call stack.
Blocking The Main Thread
- Any operation that blocks the call stack is referred to as blocking the main thread.
- Never block the main thread.
Always try to use asynchronous operations for tasks that take time, such as setTimeout.
Credits to Akshay Saini.
Top comments (0)