Created
March 24, 2015 14:53
-
-
Save leifoolsen/0002af2977954d6435b9 to your computer and use it in GitHub Desktop.
Function in javascript that can be called only once
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Function in javascript that can be called only once | |
// See e.g : http://davidwalsh.name/javascript-once | |
// http://stackoverflow.com/questions/12713564/function-in-javascript-that-can-be-called-only-once | |
function once(fn, context) { | |
var result; | |
return function() { | |
if(fn) { | |
result = fn.apply(context || this, arguments); | |
fn = null; | |
} | |
return result; | |
}; | |
} | |
(function() { | |
var canOnlyFireOnce = once(function() { | |
console.log('Fired!'); | |
}); | |
canOnlyFireOnce(); // "Fired!" | |
canOnlyFireOnce(); // nada | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment