Is there a way to run a piece of JavaScript code only ONCE, without using boolean flag variables to remember whether it has already been ran or not?
Specifically not something like:
var alreadyRan = false;
function runOnce() {
if (alreadyRan) {
return;
}
alreadyRan = true;
/* do stuff here */
}
I’m going to have a lot of these types of functions and keeping all booleans would be messy…
An alternative way that overwrites a function when executed so it will be executed only once.
‘Useful’ example:
Edit: as CMS pointed out, just overwriting the old function with
function(){}will create a closure in which old variables still exist. To work around that problem,function(){}is replaced byFunction(""). This will create an empty function in the global scope, avoiding a closure.