简体   繁体   English

在一段时间后重复执行功能的良好模式是什么?

[英]What is the good pattern to execute a function repeated after some time?

Using setInterval/ setTimeout, how can I make sure my function FINISH executing before waiting for some time and then executing again, FINISH, then wait, and so on. 使用setInterval / setTimeout,如何确保我的函数FINISH在等待一段时间后执行,然后再次执行,FINISH,然后等待,依此类推。 Thanks. 谢谢。

That's the classic use case for a chained series of setTimeout : 这是一系列setTimeout的经典用例:

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

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

Since setTimeout only schedules a single call to the function, you reschedule it (if appropriate) after the function has done its work. 由于setTimeout仅安排对函数的单个调用,因此您在函数完成工作后重新安排它(如果适用)。

Unlike setInterval , this works correctly even if the work your function does is asynchronous, as long as you reschedule it from the callback of the asynchronous work. setInterval不同,即使您的函数所做的工作是异步的,只要您从异步工作的回调中重新安排它,它也可以正常工作。 For example: 例如:

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

In contrast, if you're doing something asynchronous, using setInterval rapidly becomes chaotic. 相反,如果您正在执行异步操作,则使用setInterval很快变得混乱。

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

Usage : 用法:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM