gpt4 book ai didi

javascript - 将 setTimeout 放置在带有 if 条件的 setTimeout 中

转载 作者:行者123 更新时间:2023-12-03 09:33:06 26 4
gpt4 key购买 nike

我有两个 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秒内运行,否则,它将尽快触发。

我用了ternary operator ,这里:

var delay = (batchID.length === 2) ? 50000 : 0;

这是以下内容的缩写:

var delay;
if(batchID.length === 2){
delay = 50000;
} else {
delay = 0;
}

关于javascript - 将 setTimeout 放置在带有 if 条件的 setTimeout 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31432732/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com