Skip to content

Instantly share code, notes, and snippets.

@czterystaczwarty
Created September 16, 2015 21:37
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 czterystaczwarty/203c93840050e975de3f to your computer and use it in GitHub Desktop.
Save czterystaczwarty/203c93840050e975de3f to your computer and use it in GitHub Desktop.
The `once` function ensures a given function can only be called once, thus prevent duplicate initialization!
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment