Skip to content

Instantly share code, notes, and snippets.

@Tigraine
Created May 22, 2011 20:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Tigraine/985884 to your computer and use it in GitHub Desktop.
Save Tigraine/985884 to your computer and use it in GitHub Desktop.
Once function in JS
once = (func) ->
calls = 0
->
calls+=1
if (calls > 1)
throw "baad girl"
func.apply(this, arguments)
m = once -> alert "hello"
m()
m()
var m, once;
once = function(func) {
var calls;
calls = 0;
return function() {
calls += 1;
if (calls > 1) {
throw "baad girl";
}
return func.apply(this, arguments);
};
};
m = once(function() {
return alert("hello");
});
m();
m();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment