Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript running code once

Tags:

javascript

I only want my JavaScript to run once, but I cannot control how many times the javascript file is executed. Basically I'm writing a tiny JS snippet into a CMS, and the CMS is actually calling it 5-10 times. So solutions like this:

function never_called_again(args) {
  // do some stuff
  never_called_again = function (new_args) {
   // do nothing
  }
}
never_called_again();

Don't seem to work because as soon as my snippet is run again from the top the function is re-declared, and 'do some stuff' is re-evaluated. Perhaps I'm just not doing it properly, I'm not great with JS. I'm considering using something like try-catch on a global variable, something like

if (code_happened == undefined) {
    \\ run code
     code_happened = true;
}

EDIT: There is a consistent state e.g. if I set a variable I can see when my snippet is run again. But having to declare it before I access it, I don't know how to say 'does this variable exist yet'

like image 339
Hamy Avatar asked Jan 23 '13 00:01

Hamy


1 Answers

if (typeof code_happened === 'undefined') {
  window.code_happened = true;
  // Your code here.
}

The typeof check gets you around the fact that the global hasn't been declared. You could also just do if (!window.code_happened) since property access isn't banned for undefined properties.

like image 102
Mike Samuel Avatar answered Sep 19 '22 14:09

Mike Samuel