Skip to content

Instantly share code, notes, and snippets.

@ahliang85
Created September 7, 2015 03:55
Show Gist options
  • Save ahliang85/c5f64cefdac40d5f9c2c to your computer and use it in GitHub Desktop.
Save ahliang85/c5f64cefdac40d5f9c2c to your computer and use it in GitHub Desktop.
JavaScript - Once Function
// http://davidwalsh.name/javascript-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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment