使用if条件在setTimeout中放置setTimeout

时间:2015-07-15 14:06:43

标签: javascript

我有以下两个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()。所以只是想知道我是否必须重复它,或者我可以使用其他逻辑。

谢谢。

1 个答案:

答案 0 :(得分:1)

您可以根据条件更改超时延迟:

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;
}