[英]How to have a function call itself only once?
这段代码不断重复,但是我希望它在函数调用之后,然后在使用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);
例如。
你可以试试这个吗
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();
您可以在此处应用条件逻辑。
var callfunc = true;
function alertit() {
alert('code');
if(callfunc == true)
setTimeout(function(){ callfunc = false; alertit();}, 200);
}
alertit();
如果对setTimeout
的调用必须在内部:
function alertit() {
var f = function () {
alert('code');
}
f();
setTimeout(f, 200);
}
alertit();
您可以使用两个标志来实现。 count将确保您的方法运行两次,并且execute标志确保仅首次设置超时。
var execute = true;
var count = 0;
function alertit() {
if (count < 2) {
alert('code');
if (execute) {
setTimeout(alertit, 200);
execute = false;
}
}
}
alertit();
我看到我给出了类似tangelo的类似答案,该答案通过简单,简单的步骤完成。
如果您对更通用的方法感兴趣,可以设置以下内容:
function callMultipleTimes(func, count, delay) {
var key = setInterval(function(){
if (--count <= 0) {
clearInterval(key);
}
func();
}, delay);
}
function alertit() {
alert('code');
}
callMultipleTimes(alertit, 2, 200);
创建一个全局变量调用_Count = 0,并在函数alertit()中执行if条件,如果(_Count <> 1)调用该函数,然后如果此条件为true,则递增变量并调用该函数...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.