Skip to content

Instantly share code, notes, and snippets.

@kylehill
Created July 12, 2016 20:45
Show Gist options
  • Save kylehill/9ca1458cc77acc8073bcc196543e133f to your computer and use it in GitHub Desktop.
Save kylehill/9ca1458cc77acc8073bcc196543e133f to your computer and use it in GitHub Desktop.
// 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()
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