Skip to content

Instantly share code, notes, and snippets.

@Gattermeier
Created April 25, 2016 14:51
Show Gist options
  • Save Gattermeier/f5b6682834d9756a324b00d70e7b840b to your computer and use it in GitHub Desktop.
Save Gattermeier/f5b6682834d9756a324b00d70e7b840b to your computer and use it in GitHub Desktop.
memoize a function to only fire once.
var once = function(func) {
var alreadyCalled = false;
return function() {
if (!alreadyCalled) {
func.apply(this, arguments);
alreadyCalled = true;
}
};
};
@Gattermeier
Copy link
Author

To 'memoize' a function pass it as parameter into function 'once'.
For instance:

var say = function(what) {
  console.log(what)
}

var sayonce = once(say); // => returns memoized version of function say

sayonce('what') // => will console log 'what'
sayonce('no more') // => will not fire again

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