xxxxxxxxxx
function sum(num1,num2,callback){
let total = num1 + num2
callback(total)
}
sum(10,20,function(total){
// received total here
console.log(total);
})
sum(5,16,(total)=>{
console.log(total);
})
xxxxxxxxxx
/*
A callback function is a function passed into another function
as an argument, which is then invoked inside the outer function
to complete some kind of routine or action.
*/
function greeting(name) {
alert('Hello ' + name);
}
function processUserInput(callback) {
var name = prompt('Please enter your name.');
callback(name);
}
processUserInput(greeting);
// The above example is a synchronous callback, as it is executed immediately.
xxxxxxxxxx
function greeting(name) {
alert('Hello ' + name);
}
function processUserInput(callback) {
var name = prompt('Please enter your name.');
callback(name);
}
processUserInput(greeting);
xxxxxxxxxx
// What is callback functions in js
// Lets make a function
// Putting parameter in it "callback"
function func1(callback) {
console.log(callback); // Log 'callback'; And now our parameter callback is a function and we can call it from our func1 and this is what callback is
hello();
}
// Making one more function to print hello world in console
function hello() {
console.log("Hello world");
}
func1(hello); // Call func and give hello function as a arguement; Yes we can give function as arguement
// func1(hello()); // This is wrong way to give function as arguement
xxxxxxxxxx
function greeting(name) {
alert('Hello ' + name);
}
function processUserInput(callback , {
var name = prompt('Please enter your name.');
callback(name);
}}
processUserInput(greeting);
xxxxxxxxxx
// A callback function is a function that is passed as an argument to another function
// and is expected to be called back (executed) at a certain point within the containing function.
// It allows you to define an action to be taken after a certain task or event has been completed.
// Example of a callback function
function sayHello(name, callback) {
console.log('Hello, ' + name);
callback();
}
function sayGoodbye() {
console.log('Goodbye!');
}
sayHello('John', sayGoodbye);
xxxxxxxxxx
// A function that accepts a callback function as an argument
function performTask(callback) {
// Simulating an asynchronous task
setTimeout(function() {
// Perform some task
console.log('Task completed');
// Execute the callback function
callback();
}, 2000);
}
// Define the callback function
function afterTaskCompletion() {
console.log('Callback function executed');
}
// Call the performTask() function and pass the callback
performTask(afterTaskCompletion);
xxxxxxxxxx
// Example using callback in JavaScript
function greetUser(name, callback) {
console.log("Hello, " + name);
callback();
}
function finishGreeting() {
console.log("Greeting finished.");
}
// Usage
greetUser("John", finishGreeting);