Skip to content

Instantly share code, notes, and snippets.

@amitmbee
Created January 27, 2018 07:15
Show Gist options
  • Save amitmbee/1472fc6be0f1bbb41043b22c921bc861 to your computer and use it in GitHub Desktop.
Save amitmbee/1472fc6be0f1bbb41043b22c921bc861 to your computer and use it in GitHub Desktop.
Once - Can call a callback(eventHandlers mostly) only once, returns undefined the second time
//once
//There are times when you prefer a given functionality only happen once, similar to the way you'd use an onload event. //This code provides you said functionality:
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
//How it Works
//A function is passed to once(fn) as an argument. once() executes the callback function once and assignes null as the value of callback. Since, Javascript function are passed by reference, fn=null means the the original callback function also points to a null value. Hence the callback cannot be fired the second time
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment