Skip to content

Instantly share code, notes, and snippets.

@petermac-
Last active September 12, 2015 19:14
Show Gist options
  • Save petermac-/a8c9ad6a1c7ec3bdb6e3 to your computer and use it in GitHub Desktop.
Save petermac-/a8c9ad6a1c7ec3bdb6e3 to your computer and use it in GitHub Desktop.
once.js
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

There are times when you prefer a given functionality only happen once, similar to the way you'd use an onload event. The once function ensures a given function can only be called once, thus prevent duplicate initialization!

From http://davidwalsh.name/essential-javascript-functions

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment