Javascript 清除间隔并在x秒后再次设置
我想用Javascript 清除间隔并在x秒后再次设置,javascript,Javascript,我想用执行简单间隔,如果,则检查变量的值并再次执行函数() 再次函数包含清除间隔,i++和设置超时在x秒后再次调用间隔 var speed = 1000; var wait = 0; var i = 0; function init() { setInterval(function() { if (i >= 6) i = 0; if (i == 4) { wai
执行简单间隔,如果,则检查变量的值并再次执行函数(
)
再次
函数包含清除间隔
,i++
和设置超时
在x
秒后再次调用间隔
var speed = 1000;
var wait = 0;
var i = 0;
function init() {
setInterval(function() {
if (i >= 6) i = 0;
if (i == 4) {
wait = 5000;
again(wait);
} else {
document.body.innerHTML = i;
i++;
}
}, speed);
}
function again(time) {
clearInterval(init());
i++;
setTimeout(function() {
setInterval(init(), speed);
}, time);
}
init();
我希望输出如下:
1, 2, 3, Waiting x sec's , 5, 1, 2, ...
但是代码正在做一些疯狂的事情,它的速度越来越快。我不知道为什么
下面是一个示例(可能会使浏览器崩溃!)
你能修好并解释一下吗?谢谢您不是在清除间隔,而是在clearInterval方法中使用函数。所使用的方法init没有返回语句,所以clearInterval在属性中未定义,所以它不清除任何内容
固定代码:
var speed = 1000;
var wait = 0;
var i = 0;
var interval=null;
function init() {
interval = setInterval(function() {
if (i >= 6) i = 0;
if (i == 4) {
wait = 5000;
again(wait);
} else {
document.body.innerHTML = i;
i++;
}
}, speed);
}
function again(time) {
clearInterval(interval);
i++;
setTimeout(function() {
init()
}, time);
}
init();
函数setInterval返回区间id,属性中的函数clearInterval应该获取要停止的区间id,因此我创建了区间变量来保存id。我正在clearInterval中使用此变量。这是一个如何更改setInterval
调用延迟的小示例
(function iife() {
var timer = null,
counter = 0;
function task() {
counter += 1;
console.log(counter);
// condition: every four reps
if (counter % 4 === 0) {
console.log("changed speed to 4 seconds");
return start(4000);
}
// condition: every seven reps
if (counter % 7 === 0) {
console.log("changed speed to 2 seconds");
return start(2000);
}
}
function start(delay) {
clearInterval(timer);
console.log("runs every " + delay + " miliseconds");
timer = setInterval(task, delay);
}
start(1000);
}());
clearInterval(init())代码>不清除间隔。事实上,它设置了一个新的选项。该选项使用var x=setInterval(function(){},然后使用clearInterval(x);仍然不起作用setInterval
返回一个ID。给clearInterval
该ID以停止循环。例如:var ID=setInterval(init,time);clearInterval(ID)
setInterval(init(),speed)
也将是一个问题-您希望传递函数,而不是调用它:setInterval(init,speed);
并从setInterval
调用init
,然后调用setInterval
…您确定这就是您想要的吗?