how to create a function with callback javascript code example

Example 1: 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 2: what are callbacks

/*
tl;dr: Callbacks are a way to force one function to complete,
before running another. Used for asynchronus programming.
*/

// Consider this example:
  
names = ['Anthony', 'Betty', 'Camie']

function addName(name, callback){
	setTimeout(function(){
    	names.append(name)
      	callback()
    }, 200)
}

function getNames(){
	setTimeout(function(){
    	console.log(names)
    }, 100)
}

addName('Daniel', getNames)
/* 
addName('Daniel', getNames) is saying:
'finish the function addName() BEFORE running the function getNames()'

> 'getNames()' here is the callback

Without the call back in this example, getNames would finish 
before addName. (setTimeout is used to force one function to go slower)

Callbacks are given as arguments to other functions

*/

Tags:

Misc Example