我有一个奇怪的问题,我试图用setInterval做一个循环,但是我也想在里面有一个SetTimeout。
发布于 2017-11-30 04:18:27
从评论来看,你需要的只是
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);
}https://stackoverflow.com/questions/47565627
复制相似问题