Created
February 21, 2016 17:27
-
-
Save chrisblakley/0796eab6cd6d34486c10 to your computer and use it in GitHub Desktop.
A function that allows other functions to be called only one time per page load.
This file contains hidden or 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
function once(fn, args, unique){ | |
if ( typeof onces === 'undefined' ){ | |
onces = {}; | |
} | |
if ( typeof fn === 'function' ){ //If the first parameter is a function | |
if ( typeof args === 'string' ){ //If no parameters | |
args = []; | |
unique = args; | |
} | |
if ( typeof onces[unique] === 'undefined' || !onces[unique] ){ | |
onces[unique] = true; | |
return fn.apply(this, args); | |
} | |
} else { //Else return boolean | |
unique = fn; //If only one parameter is passed | |
if ( typeof onces[unique] === 'undefined' || !onces[unique] ){ | |
onces[unique] = true; | |
return true; | |
} else { | |
return false; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Careful,
onces
becomes a global var.