我有一个 setInterval 循环。它设置为 3500 毫秒,如下所示:-
var loop = setInterval(function() { /*stuff*/ }, 3500);
如果发生某种情况,在“东西”的某个时刻,我想强制循环进行新的迭代,而不是等待 3500 毫秒。这怎么可能?是继续还是我只需要以不同的方式构建流程?
我有一个 setInterval 循环。它设置为 3500 毫秒,如下所示:-
var loop = setInterval(function() { /*stuff*/ }, 3500);
如果发生某种情况,在“东西”的某个时刻,我想强制循环进行新的迭代,而不是等待 3500 毫秒。这怎么可能?是继续还是我只需要以不同的方式构建流程?
setTimeout
您可以尝试使用而不是编写匿名自调用函数setInterval
:
var i = 0;
(function() {
// stuff
i++;
if (i % 2 == 0) {
// If some condition occurs inside the function, then call itself once again
// immediately
arguments.callee();
} else {
// otherwise call itself in 3 and a half seconds
window.setTimeout(arguments.callee, 3500);
}
})(); // <-- call-itself immediately to start the iteration
更新:
由于在评论部分表达了反对使用的分歧arguments.callee
,这里是如何使用命名函数来实现相同的:
var i = 0;
var doStuff = function() {
// stuff
i++;
if (i % 2 == 0) {
// If some condition occurs inside the function, then call itself once again
// immediately
doStuff();
} else {
// otherwise call itself in 3 and a half seconds
window.setTimeout(doStuff, 3500);
}
};
doStuff();
你可以使用这样的东西......使用setTimeout
而不是setInterval
......
<script type="text/javascript">
var show;
var done = false;
show = setTimeout(showHideForm, 3500);
function showHideForm() {
// Do something
if(done) {
clearTimeout(show);
show = setTimeout(showHideForm, 2000);
}
}
</script>
clearTimeout
将返回的句柄作为参数setTimeout
。
Use a named function and call it when you want.
var loop = setInterval(loopFunc, 3500);
function loopFunc(){
//do something
}
function anticipate(){
clearInterval(loop); //Stop interval
loopFunc(); //Call your function
loop = setInterval(loopFunc, 3500); //Reset the interval if you want
}
function looper(t) {
var loop = setInterval(function() {
document.write(s++);
if (mycondition) { // here is your condition
loopagain(200); // specify the time which new loop will do
loop = window.clearInterval(loop); // clear the first interval
return; // exit from this function!
}
}, t);
}
window.onload = looper(1000); // this will have default setInterval function time ans will start at window load!
function loopagain(t) {
looper(t);
}
My contrived example:
var time = 3500,
loops = 0,
loop;
(function run(){
var wait = time,
dontwait = false;
if (loops++ == 5) {
loops = 0;
dontwait = 1000;
}
console.log('Interval: ', dontwait || wait);
return loop = setTimeout(run, dontwait || wait);
})();
Basically, a self-invoking function looping back on a self-calling function, with (!) shorthand variable switching. Nifty.