[英]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.