Javascript code runs once

I want my JavaScript to run once , but . I can not control how many times the javascript file is executed. Basically I write a tiny fragment of JS in CMS, and CMS actually calls it 5-10 times. So, such solutions:

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

It doesn’t work, because as soon as my fragment starts again from above, the function is re-declared, and “do some things” is re-evaluated. Maybe I'm just not doing it right, I don't really like JS. I am considering using something like try-catch for a global variable, something like

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

EDIT: There is a consistent state, for example. if I set a variable, I can see when my fragment is running again. But, to declare it before I receive it, I don’t know how to say "does this variable exist"

+7
source share
4 answers

Try the following:

 var doneTheStuff; function whatever() { if (!doneTheStuff) { doneTheStuff = true; // do the stuff } } 

Reserved variable declarations do not affect the value of a variable. Once one of the functions set the variable to true , the rest will do nothing.

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

In the typeof test, you will find out that the global is not declared. You can also just do if (!window.code_happened) , since access to properties is not forbidden for undefined properties.

+3
source

Use closure and set the flag. If the flag is true , just return:

 if ( ! window.never_called_again ) { window.never_called_again = (function () { var ran = false; return function (args) { if ( ran ) return; ran = true; // Do stuff }; }()); } 

Here's the fiddle: http://jsfiddle.net/U2NCs/

+2
source

Using jQuery, the .one () function can be useful: http://api.jquery.com/one/

W3School here: http://www.w3schools.com/jquery/event_one.asp

+2
source

All Articles