SetInterval中的SetTiemout?

时间:2017-11-30 03:57:56

标签: javascript jquery

我有一个奇怪的问题,我正在尝试使用setInterval进行循环,但我想在内部也有一个SetTimeout。

1 个答案:

答案 0 :(得分:2)

从评论中看,您需要的只是

var init = function() {
    setTimeout(function(){ 
        console.log("Hi");
        init(); // only call init here to start again if need be
    }, 8000);
}
init();
  

根据下面的评论,我假设间隔需要“暂停”,因为在你的评论中你说at some point, I have to delay one action - 这意味着这种延迟并不总是必要的。鉴于此,您可以按如下方式编写

var test = function() {
    var interval = setInterval(function() {
        if (someCondition) {
           clearInterval(interval); // stop the interval
            setTimeout(function(){ 
                console.log("Hi");
                test(); // restart the interval
            }, 8000);

        } else {
            // this is done every second, except when "someCondition" is true
        }
    }, 1000);
}

甚至

var running = true;
var test = function() {
    var interval = setInterval(function() {
        if (someCondition) {
           running = false; // stop the interval
            setTimeout(function(){ 
                console.log("Hi");
                running = true; // restart the interval
            }, 8000);

        } else if (running) {
            // this is done every second, only when "running" is true
        }
    }, 1000);
}