Reputation: 65
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
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
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
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
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
Reputation: 152266
You can try with:
var first_time = true;
function myFunction(){
if (first_time){
first_time = false;
// ...
} else {
// ...
}
}
Upvotes: 1