[英]Placing setTimeout within setTimeout with an if condition
我有兩個setTimouts如下,根據一個if
條件,我想跳過一個超時。
var batchID = [];
batchID = getBatchIDs();//this function gets me the batch IDs
setTimeout(function() {
//I get the batchIDs in the first 30 seconds.
//here i want to put a check, if(batchID.length === 2)
//{I want the script to wait for another 50 seconds}
//else {proceed with func1 and func2}
setTimeout(function() {
func1();
func2();
}, 50000);
},30000);
那么這是正確的做法嗎:
setTimeout(function() {
if(batchID.length === 2) {
setTimeout(function() {
func1();
func2();
}, 50000);
} else {
func1();
func2();
};
},30000);
因為我有很多代碼代替func1()
和func2()
。 所以只是想知道我是否必須重復它,否則我可以使用其他邏輯。
謝謝。
您可以根據情況更改超時延遲:
setTimeout(function() {
var delay = (batchID.length === 2) ? 50000 : 0;
setTimeout(function() {
func1();
func2();
}, delay);
},30000);
如果batchID.length === 2
,則超時將在50秒內運行,否則,它將盡快觸發。
我在這里使用了三元運算符 :
var delay = (batchID.length === 2) ? 50000 : 0;
這是以下方面的簡寫:
var delay;
if(batchID.length === 2){
delay = 50000;
} else {
delay = 0;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.