Skip to content

Instantly share code, notes, and snippets.

@ppscvalentin
Created May 25, 2016 12:05
Show Gist options
  • Save ppscvalentin/ad63350274bfa98300937132ea0b070f to your computer and use it in GitHub Desktop.
Save ppscvalentin/ad63350274bfa98300937132ea0b070f to your computer and use it in GitHub Desktop.
Apply function once
function once(fn, context) {
var result;
return function() {
if(fn) {
result = fn.apply(context || this, arguments);
fn = null;
}
return result;
}
}
// Usage
var canOnlyFireOnce = once(function() {
console.log('Fired!');
});
canOnlyFireOnce(); // "Fired!"
canOnlyFireOnce(); // nada
/*
Many JavaScript toolkits offer this as a feature but the code
to accomplish this feat is so small that it's good to have
available in the case that you can dodge a JavaScript toolkit!
- David Walsh, https://davidwalsh.name/javascript-once
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment