12

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'

1
  • 2
    "I don't know how to say 'does this variable exist yet?'" - typically this is done with var foo = window.foo || {} Commented Jan 23, 2013 at 0:57

5 Answers 5

28

Try this:

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

Redundant variable declarations don't affect the value of the variable. Once one of the functions has set the variable to true, the others won't do anything.

Sign up to request clarification or add additional context in comments.

3 Comments

Works! Followup question - it seems to run the last declared function e.g. make do the stuff do alert(1) and alert(2) and you will only see 2. Doesn't matter for me (they are all the same), but fascinating anyways
@Hamy - My solution would work in reverse. Only the first declared function will run.
@Hamy if the code is generated into the same <script> block that would happen; if however there are multiple <script> blocks, it'll run the last one in the first of the scripts. Function declarations in JavaScript are always treated as if they appeared at the very top of their enclosing scope.
9
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.

Comments

2

Use a closure, and set a 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/

4 Comments

But if that shows up in two separate bits of JavaScript, it'll have the same problem.
The entire file is being executed multiple times, including defining the function, if I understand the OP's description. This is a truer representation, and it does get called multiple times: jsfiddle.net/Qn52E.
As others pointed out, I'm more similar to mellamokb's comment, so this doesn't seem to work ;-)
I missed that. I updated my answer. @Pointy's is more concise, but introduces an extra global variable.
2

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

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

Comments

0

In this way, the code is executed only once.

if(typeof onceRun == "undefined") window.onceRun=(
    ()=>{
        //your codes...
        console.log("runing...")
    return true
    }).call()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.