简体   繁体   English

如何仅一次调用一个函数?

[英]How to have a function call itself only once?

This code keeps repeating, but i want it to happen twice, after the functions call and then after the set period of time using setTimeout . 这段代码不断重复,但是我希望它在函数调用之后,然后在使用setTimeout的设置时间段后发生两次。

function alertit() {
     alert('code');
     setTimeout(alertit, 200);
}

alertit();
function alertit(callAgain) {
     alert('code');
     if (callAgain) setTimeout("alertit(false)", 200);
}

alertit(true);
function alertit() {
     alert('code');
}

alertit();
setTimeout(alertit, 200);

for example. 例如。

Could you try this 你可以试试这个吗

function alertit(){

    // guard code
    if ( alertit.times == 2 ) return ; // for 4 times, alertit.times == 4  
    alertit.times = alertit.times ?  ++alertit.times: 1;

    // your function logic goes here ..   
    alert( 'here function called ' + alertit.times  );

    setTimeout( alertit , 1000 );
}

alertit();

You can apply condition logic over here. 您可以在此处应用条件逻辑。

    var callfunc = true;
    function alertit() {
         alert('code');
      if(callfunc == true)
         setTimeout(function(){ callfunc = false; alertit();}, 200);
    }

    alertit();

if the call to setTimeout has to be inside: 如果对setTimeout的调用必须在内部:

function alertit() {
  var f = function () {
    alert('code');
  }
  f();
  setTimeout(f, 200);
}

alertit();

You can use two flags to achieve. 您可以使用两个标志来实现。 count will make sure your method runs for two times and the execute flag makes sure only first time the timeout is set. count将确保您的方法运行两次,并且execute标志确保仅首次设置超时。

var execute = true;
var count = 0;

function alertit() {
    if (count < 2) {
        alert('code');
        if (execute) {
            setTimeout(alertit, 200);
            execute = false;
        }
    }

}

alertit();

I see I have given a similar answer like tangelo which is doing the same in simple, easy steps. 我看到我给出了类似tangelo的类似答案,该答案通过简单,简单的步骤完成。

If you are interested in a more general approach, you could set up something like this: 如果您对更通用的方法感兴趣,可以设置以下内容:

function callMultipleTimes(func, count, delay) {
    var key = setInterval(function(){
        if (--count <= 0) {
            clearInterval(key);
        }
        func();
    }, delay);
}

function alertit() {
     alert('code');
}

callMultipleTimes(alertit, 2, 200);

FIDDLE 小提琴

创建一个全局变量调用_Count = 0,并在函数alertit()中执行if条件,如果(_Count <> 1)调用该函数,然后如果此条件为true,则递增变量并调用该函数...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM