Javascript:强制setInterval中的新循环迭代

时间:2012-12-28 13:06:29

标签: javascript loops setinterval

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

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

如果发生某种情况,在'stuff'中的某一点,我想强制循环的新迭代并且不等待3500毫秒。怎么可能?是继续还是只需要以不同的方式构建流程?

5 个答案:

答案 0 :(得分:2)

您可以尝试使用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();

答案 1 :(得分:2)

您可以使用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>

clearTimeoutsetTimeout返回的句柄作为参数。

答案 2 :(得分:1)

使用命名函数并在需要时调用它。

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
}

答案 3 :(得分:0)

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);
}​

http://jsfiddle.net/tFCZP/

答案 4 :(得分:0)

我做出的例子:

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

http://jsfiddle.net/NX43d/1/

基本上,一个自调用函数循环回一个自调用函数,带有(!)速记变量切换。漂亮的。