Skip to content

Instantly share code, notes, and snippets.

@dima-f1
Created June 14, 2015 13:18
Show Gist options
  • Select an option

  • Save dima-f1/be0d5c9001fab8ff8d39 to your computer and use it in GitHub Desktop.

Select an option

Save dima-f1/be0d5c9001fab8ff8d39 to your computer and use it in GitHub Desktop.
Javascript function that will run only 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(); // undefined
@dima-f1
Copy link
Author

dima-f1 commented Jun 14, 2015

There are times when you prefer a given functionality only happen once, similar to the way you'd use an onload event

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