Skip to content

Instantly share code, notes, and snippets.

@leifoolsen
Created March 24, 2015 14:53
Show Gist options
  • Save leifoolsen/0002af2977954d6435b9 to your computer and use it in GitHub Desktop.
Save leifoolsen/0002af2977954d6435b9 to your computer and use it in GitHub Desktop.
Function in javascript that can be called only once
// Function in javascript that can be called only once
// See e.g : http://davidwalsh.name/javascript-once
// http://stackoverflow.com/questions/12713564/function-in-javascript-that-can-be-called-only-once
function once(fn, context) {
var result;
return function() {
if(fn) {
result = fn.apply(context || this, arguments);
fn = null;
}
return result;
};
}
(function() {
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