When you call a function in another function, it is known as a callback function
.
Easy example would be:
function hellojs(){
console.log("Hi Javascript callback");
}
function call(hello){
console.log("Hi user!")
hello();
}
call(hellojs)
Simply prints "Hi user!" and then "Hi Javascript callback". This is a synchronous callback.
As a developer, an API call with .then is generally where async callbacks come to play.
Why are they important though?
Web APIs like setTimeout()
are used to time particular callback functions without blocking the main call stack. Like this, there is no function just idle and sitting in call stack and blocking it.
Another example if adding an event handler on any object, let's say an image here:
document.getElementById("random")
.addEventListener('mouseover', function(){
console.log("Hovered on image")
});
Here the function is called when there is hovering on the image (random is the id given to the img tag). This function then appears on the call stack and is executed.
Web APIs, aynchronous Javascript, event listeners, there are a lot of keywords that have been mentioned here which will be discussed in the upcoming posts!
Top comments (0)