1

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

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

如果发生某种情况,在“东西”的某个时刻,我想强制循环进行新的迭代,而不是等待 3500 毫秒。这怎么可能?是继续还是我只需要以不同的方式构建流程?

4

5 回答 5

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();
于 2012-12-28T13:12:18.830 回答
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>

clearTimeout将返回的句柄作为参数setTimeout

于 2012-12-28T13:18:09.730 回答
1

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
}
于 2012-12-28T13:19:14.327 回答
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/

于 2012-12-28T13:20:28.053 回答
0

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

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

Basically, a self-invoking function looping back on a self-calling function, with (!) shorthand variable switching. Nifty.

于 2012-12-28T13:34:41.250 回答