1/*
2A callback function is a function passed into another function
3as an argument, which is then invoked inside the outer function
4to complete some kind of routine or action.
5*/
6function greeting(name) {
7 alert('Hello ' + name);
8}
9
10function processUserInput(callback) {
11 var name = prompt('Please enter your name.');
12 callback(name);
13}
14
15processUserInput(greeting);
16// The above example is a synchronous callback, as it is executed immediately.
1function greeting(name) {
2 alert('Hello ' + name);
3}
4
5function processUserInput(callback) {
6 var name = prompt('Please enter your name.');
7 callback(name);
8}
9
10processUserInput(greeting);
1// A function which accepts another function as an argument
2// (and will automatically invoke that function when it completes - note that there is no explicit call to callbackFunction)
3funct printANumber(int number, funct callbackFunction) {
4 printout("The number you provided is: " + number);
5}
6
7// a function which we will use in a driver function as a callback function
8funct printFinishMessage() {
9 printout("I have finished printing numbers.");
10}
11
12// Driver method
13funct event() {
14 printANumber(6, printFinishMessage);
15}
16
1function add(a, b, callback) {
2 if (callback && typeof(callback) === "function") {
3 callback(a + b);
4 }
5}
6
7add(5, 3, function(answer) {
8 console.log(answer);
9});
1/*
2tl;dr: Callbacks are a way to force one function to complete,
3before running another. Used for asynchronus programming.
4*/
5
6// Consider this example:
7
8names = ['Anthony', 'Betty', 'Camie']
9
10function addName(name, callback){
11 setTimeout(function(){
12 names.append(name)
13 callback()
14 }, 200)
15}
16
17function getNames(){
18 setTimeout(function(){
19 console.log(names)
20 }, 100)
21}
22
23addName('Daniel', getNames)
24/*
25addName('Daniel', getNames) is saying:
26'finish the function addName() BEFORE running the function getNames()'
27
28> 'getNames()' here is the callback
29
30Without the call back in this example, getNames would finish
31before addName. (setTimeout is used to force one function to go slower)
32
33Callbacks are given as arguments to other functions
34
35*/
1function greeting(name) {
2 alert('Hello ' + name);
3}
4
5function processUserInput(callback , {
6 var name = prompt('Please enter your name.');
7 callback(name);
8}}
9
10processUserInput(greeting);