Created
January 22, 2016 02:05
-
-
Save jll90/2597f3336d40251cfb61 to your computer and use it in GitHub Desktop.
Example of JavaScript callbacks.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// executes a single function | |
function single(callback){ | |
callback(); | |
} | |
function b(){ | |
console.log("I'm b"); | |
} | |
function d(){ | |
console.log("I'm d"); | |
} | |
//prints: I'm b | |
single(b); | |
//prints: I'm d | |
single(d); | |
// pass multiple functions | |
function multiple(fns){ | |
if (fns.constructor === Array){ | |
var length = fns.length; | |
for (i = 0; i < length; i++){ | |
fns[i](); //executes ith function | |
} | |
} else{ | |
fns(); //executes the function passed to it | |
} | |
} | |
// prints I'm b | |
multiple(b); | |
// prints I'm b followed by I'm d | |
multiple([b,d]); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment