Created
June 14, 2015 13:18
-
-
Save dima-f1/be0d5c9001fab8ff8d39 to your computer and use it in GitHub Desktop.
Javascript function that will run only once
This file contains hidden or 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 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 |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
There are times when you prefer a given functionality only happen once, similar to the way you'd use an onload event