callback example

Example 1: call back function in javascript

function greeting(name) {
  alert('Hello ' + name);
}

function processUserInput(callback) {
  var name = prompt('Please enter your name.');
  callback(name);
}

processUserInput(greeting);

Example 2: 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 3: 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 4: callback in js

function greeting(name) {
  alert('Hello ' + name);
}

function processUserInput(callback , {
  var name = prompt('Please enter your name.');
  callback(name);
}}

processUserInput(greeting);

Example 5: callback function

function createQuote(quote, callback){ 
  var myQuote = "Like I always say, " + quote;
  callback(myQuote); // 2
}

function logQuote(quote){
  console.log(quote);
}

createQuote("eat your vegetables!", logQuote); // 1

// Result in console: 
// Like I always say, eat your vegetables!

Example 6: javascript callback function

const message = function() {  
    console.log("This message is shown after 3 seconds");
}
 
setTimeout(message, 3000);