Skip to content

Instantly share code, notes, and snippets.

@travismillerweb
Created June 30, 2014 21:40
Show Gist options
  • Save travismillerweb/0b5b67c5e4f9f82a5231 to your computer and use it in GitHub Desktop.
Save travismillerweb/0b5b67c5e4f9f82a5231 to your computer and use it in GitHub Desktop.
JS - JavaScript Fire Once Pattern
/*
JavaScript Fire Once Pattern
Courtesy of David Walsh
Reference Link: http://davidwalsh.name/javascript-once
*/
// The "once" wrapper
function once(fn, context) {
return function() {
if(!fn) return;
fn.apply(context || this, arguments);
// Set to null to allow garbage collection
fn = null;
};
}
// 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