首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >SetTiemout in SetInterval?

SetTiemout in SetInterval?
EN

Stack Overflow用户
提问于 2017-11-30 03:57:56
回答 1查看 77关注 0票数 0

我有一个奇怪的问题,我试图用setInterval做一个循环,但是我也想在里面有一个SetTimeout。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-11-30 04:18:27

从评论来看,你需要的只是

代码语言:javascript
复制
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 --这意味着这种延迟并不总是必要的。考虑到这一点,您可以按以下方式编写

代码语言:javascript
复制
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);
}

甚至是

代码语言:javascript
复制
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);
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47565627

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档