Created
July 12, 2016 20:45
-
-
Save kylehill/9ca1458cc77acc8073bcc196543e133f to your computer and use it in GitHub Desktop.
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
// Defining this variable before the function you want to be run once is executed | |
// Also setting the value to something other than what you're checking it for | |
var thisHasAlreadyRun = false | |
var someFunction = function() { | |
// First time through, the variable is defined and the value isn't true, | |
// so it skips the short-circuit return | |
if (thisHasAlreadyRun === true) { | |
return | |
} | |
// NOW set the flag to true | |
thisHasAlreadyRun = true | |
// and do the other shit | |
doSomethingYouOnlyWantDoneOnce() | |
} | |
someFunction() |
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
var someFunction = function() { | |
// thisHasAlreadyRun is not defined with "var" (or "let" in ES6) anywhere, | |
// so checking its value will always cause an exception | |
if (thisHasAlreadyRun === true) { | |
return | |
} | |
thisHasAlreadyRun = true | |
doSomethingYouOnlyWantDoneOnce() | |
} | |
someFunction() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment