Callback Function
Any function that is passed as an argument is called a callback function.
A callback is a function that is to be executed after another function has finish executing.
Far too many people are intimidated by javascript callback functions! They are simple, take this example. The
console.log function is being passed as a callback to myFunc. It gets executed when setTimeout completes. That's
all there is to it!
function myFunc(text, callback) {
setTimeout(function() {
callback(text);
}, 2000);
}
myFunc('Hello world!', console.log);
// 'Hello world!'
Functions are object in JavaScript
We can pass objects to function as parameters. We can pass and call functions inside other functions.
We can also return functions from other functions.
Why do we need callback function
Js is an event driven language.-> Instead of waiting for a response before moving on, Js will keep executing
while listening for other events.
Callbacks are a way to make sure certain code doesn't execute until other code has already finished
execution.
Call me back after you done your job.
Execute a function after another function is executed.
Anonymous Func -> function having no name.
setTimeout(function(){console.log('anonymous
function')})
setTimeout()=>{console.log('Arrow anonymous function')}
Callback functions are also used in Event Declaration.
Console
function print(callback) {
console.log("Call back function")
// print function takes a callback function as parameter and calls it inside this function.
callback()
}
const message = function () {
console.log("Hello World")
}
setTimeout(print(message), 2000)
setTimeout(message, 2000)
const perOne = (friend, callback) => {
console.log(`Hey what's up, I am talking to ${friend}. I will callback later.`)
callback()
}
const perTwo = () => {
console.log('Hey I will called you. Why did you call me?')
}
perOne('John', perTwo)
window.onload = function () {
document.getElementById("callback").addEventListener('click', function () {
console.log("Callback function")
})
}