Elise
Elise

Reputation: 65

How to determine first run of a javascript function?

I have a javascript function and I need to determine when the function run the very first time. How could I do that?

function myFunction(){
if (first_time){ //do something   }

else { ........... }

}

Upvotes: 3

Views: 4085

Answers (5)

KECG
KECG

Reputation: 106

Clearly very late to the party, I found these answers dissatisfying due to my personal performance requirements; the initial first-run conditional being wasteful (only in a hyper-optimized case, E.G. software raytracing).

I'm using the following:

function myFunction_theRest(){

   ...

}

function myFunction_first(){

   ...

   myFunction = myFunction_theRest;
}

var myFunction = myFunction_first;

Upvotes: 1

ABucin
ABucin

Reputation: 956

You could set a global variable to true, once the function has been called.

var globalVar = false;

function myFunction(){
    globalVar = true;
    if (first_time){ //do something   }

    else { ........... }

    }
}

Upvotes: 1

KooiInc
KooiInc

Reputation: 122936

You can create a pseudo static function property and check for its existence:

function myFunction(){
  if (!myFunction.didrun){ 
    //do something   
    myFunction.didrun = true;
  }
  else { ........... }
}

Upvotes: 13

ylerjen
ylerjen

Reputation: 4259

define a global var that will be incremented in each call of the function:

var nbCall= 0;
function myFunction(){
if (nbCall==0){ 
nbCall++;
 //do something   }

else { ........... }

}

Upvotes: 0

hsz
hsz

Reputation: 152266

You can try with:

var first_time = true;

function myFunction(){

  if (first_time){
    first_time = false;
    // ...
  } else {
    // ...
  }

}

Upvotes: 1

Related Questions