Vlad Holubiev
Vlad Holubiev

Reputation: 5154

How to perform if statement only at first call of function?

I have an if statement in a function. How to perform if statement only at first call of function?

Upvotes: 1

Views: 705

Answers (1)

Sergio
Sergio

Reputation: 28837

You could use this

var notFirstRun = false;
function myFunction(){
    if (notFirstRun) return; // this will "exit" the function
    else notFirstRun = true;

    if (foo == bar){ // your if statement
       // somecode
    }
    // rest of the function
}

or event more scoped:

var myFunction = (function(notFirstRun) {
    return function() {
        if (notFirstRun) return; // this will "exit" the function
        else notFirstRun = true;

        if (foo == bar) { // your if statement
            // somecode
        }
        // rest of the function
    }
})();

Upvotes: 3

Related Questions