本文介绍了Javascript:在setInterval中强制进行新的循环迭代的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个setInterval循环.设置为3500毫秒,如下所示:-

I have a setInterval loop. It's set to 3500 milliseconds, like so:-

var loop = setInterval(function() { /*stuff*/ }, 3500);

如果发生某种情况,在填充"的某一点上,我想强制循环的新迭代,并且在3500毫秒内不等待.那怎么可能?是继续吗,还是我只需要以不同的方式制定流程?

At one point in 'stuff' if a certain situation occurs, I want to force a new iteration of the loop and NOT WAIT for the 3500 milliseconds. How is that possible? Is it continue or do I just need to frame the process differently?

推荐答案

您可以尝试使用setTimeout而不是setInterval编写匿名自调用函数:

You could try writing an anonymous self-calling function using setTimeout instead of 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


更新:


UPDATE:

由于在注释部分表达了对arguments.callee用法的分歧,因此,使用命名函数可以实现相同的目的:

Due to a disagreement expressed in the comments section against the usage of arguments.callee, here's how the same could be achieved using a named function:

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();

这篇关于Javascript:在setInterval中强制进行新的循环迭代的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 08:20