最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to determine first run of a javascript function? - Stack Overflow

programmeradmin4浏览0评论

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 the if- and else-statements properly, since they are in a nested scope; it makes the code easier to read. – HelloGoodbye Commented Mar 6, 2019 at 12:06
Add a ment  | 

5 Answers 5

Reset to default 13

You 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 { ........... }

}
发布评论

评论列表(0)

  1. 暂无评论