vlad.golubev vlad.golubev - 1 month ago 8
Javascript Question

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?

Answer

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
    }
})();