Skip to content

Instantly share code, notes, and snippets.

@chrisblakley
Created February 21, 2016 17:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save chrisblakley/0796eab6cd6d34486c10 to your computer and use it in GitHub Desktop.
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.
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;
}
}
}
@TheBox193
Copy link

Careful, onces becomes a global var.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment