callback function in javascript code example
Example 1: javascript callback
/*
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.
Example 2: callback function js
function greeting(name) {
alert('Hello ' + name);
}
function processUserInput(callback) {
var name = prompt('Please enter your name.');
callback(name);
}
processUserInput(greeting);
Example 3: what are callback functions
// A function which accepts another function as an argument
// (and will automatically invoke that function when it completes - note that there is no explicit call to callbackFunction)
funct printANumber(int number, funct callbackFunction) {
printout("The number you provided is: " + number);
}
// a function which we will use in a driver function as a callback function
funct printFinishMessage() {
printout("I have finished printing numbers.");
}
// Driver method
funct event() {
printANumber(6, printFinishMessage);
}
Example 4: javascript callback
// Create a callback in the probs, in this case we call it 'callback'
function newCallback(callback) {
callback('This can be any value you want to return')
}
// Do something with callback (in this case, we console log it)
function actionAferCallback (callbackData) {
console.log(callbackData)
}
// Function that asks for a callback from the newCallback function, then parses the value to actionAferCallback
function requestCallback() {
newCallback(actionAferCallback)
}
Example 5: create callback function javascript
function add(a, b, callback) {
if (callback && typeof(callback) === "function") {
callback(a + b);
}
}
add(5, 3, function(answer) {
console.log(answer);
});
Example 6: callback in js
function greeting(name) {
alert('Hello ' + name);
}
function processUserInput(callback , {
var name = prompt('Please enter your name.');
callback(name);
}}
processUserInput(greeting);