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 { ........... }
}
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 { ........... }
}
Share
Improve this question
asked Mar 14, 2014 at 9:33
EliseElise
653 silver badges9 bronze badges
2
- 1 Does this run in a single context or does the page reload inbetween? – Liam Commented Mar 14, 2014 at 9:35
-
1
Just a note: You have accidentally ment out the closing bracket around the statements to be executed after the
if
-statement. You should also indent theif
- andelse
-statements properly, since they are in a nested scope; it makes the code easier to read. – HelloGoodbye Commented Mar 6, 2019 at 12:06
5 Answers
Reset to default 13You can create a pseudo static function property and check for its existence:
function myFunction(){
if (!myFunction.didrun){
//do something
myFunction.didrun = true;
}
else { ........... }
}
You can try with:
var first_time = true;
function myFunction(){
if (first_time){
first_time = false;
// ...
} else {
// ...
}
}
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 { ........... }
}
}
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;
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 { ........... }
}