一段时间后重复执行函数的好模式是什么?

时间:2013-01-27 00:07:54

标签: javascript settimeout setinterval

使用setInterval / setTimeout,如何确保我的函数FINISH在等待一段时间后再执行,然后再执行,然后等待,等等。感谢。

2 个答案:

答案 0 :(得分:5)

这是链式系列setTimeout

的经典用例
setTimeout(foo, yourInterval);
function foo() {
    // ...do the work...

    // Schedule the next call
    setTimeout(foo, yourInterval);
}

由于setTimeout仅调度对该函数的单个调用,因此在函数完成其工作后重新安排它(如果适用)。

setInterval不同,只要您从异步工作的回调中重新安排它,即使您的函数所做的工作是异步的,这也能正常工作。例如:

setTimeout(foo, yourInterval);
function foo() {
    callSomethingAsynchronous(function() {
        // ...we're in the async callback, do the work...

        // ...and now schedule the next call
        setTimeout(foo, yourInterval);
    });
}

相反,如果你正在做异步,那么使用setInterval会很快变得混乱。

答案 1 :(得分:0)

function execute_and_wait( repeated_function, time_delay ) {
    var next_run = function () {
        var complete_callback = function () {
            next_run();
        }
        var killcode = setTimeout(
            function () {
                repeated_function(complete_callback);
            },
            time_delay 
        );
        return killcode;
     };
     return next_run;
}

用法:

// Runs a function that prints hi every 2 seconds
// Kills it after 10 seconds
var ka = function (r) { alert('hi'); r(); };
var runka = execute_and_wait(ka,2000);
var killka = runka();
setTimeout( 
   function () {
       clearTimeout(killka);
   },
   10000
);