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

knd*_*knd 0 javascript settimeout setinterval

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

T.J*_*der 5

这是链式系列的经典用例setTimeout:

setTimeout(foo, yourInterval);
function foo() {
    // ...do the work...

    // Schedule the next call
    setTimeout(foo, yourInterval);
}
Run Code Online (Sandbox Code Playgroud)

由于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);
    });
}
Run Code Online (Sandbox Code Playgroud)

相反,如果你正在做异步,setInterval快速使用会变得混乱.