使用setTimeout()可以在指定的时间启动一个函数:

setTimeout(function, 60000);

但是如果我想多次启动这个函数呢?每当一个时间间隔过去时,我都希望执行函数(假设每60秒执行一次)。


当前回答

我倾向于调用包含循环函数的函数,该循环函数定期对自身调用setTimeout。

函数计时器(间隔 = 1000) { 函数循环(计数 = 1) { 控制台.log(计数); setTimeout(loop, interval, ++count); } 循环(); } 计时器();

其他回答

我倾向于调用包含循环函数的函数,该循环函数定期对自身调用setTimeout。

函数计时器(间隔 = 1000) { 函数循环(计数 = 1) { 控制台.log(计数); setTimeout(loop, interval, ++count); } 循环(); } 计时器();

一个订阅setInterval()并使用clearInterval()来停止永久循环的好例子:

function myTimer() {

}

var timer = setInterval(myTimer, 5000);

调用这一行来停止循环:

clearInterval(timer);
setInterval(fn,time)

是你所追求的方法。

在jQuery中,你可以这样做。

函数random_no () { var跑= math . random (); jQuery (# random_no_container) . html(跑); } setinterval(函数(){ ///调用你的函数 random_no (); }, 6000);//将Interval改为test。例如:5000秒 < script src = " https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js " > < /脚本> < div id = " random_no_container " > 你好。在这里你可以看到每6秒后的随机数 < / div >

更好地使用jAndy的答案来实现一个轮询函数,该函数每间隔秒轮询一次,并在超时秒后结束。

function pollFunc(fn, timeout, interval) {
    var startTime = (new Date()).getTime();
    interval = interval || 1000;

    (function p() {
        fn();
        if (((new Date).getTime() - startTime ) <= timeout)  {
            setTimeout(p, interval);
        }
    })();
}

pollFunc(sendHeartBeat, 60000, 1000);

更新

根据注释,将其更新为传递函数停止轮询的能力:

function pollFunc(fn, timeout, interval) {
    var startTime = (new Date()).getTime();
    interval = interval || 1000,
    canPoll = true;

    (function p() {
        canPoll = ((new Date).getTime() - startTime ) <= timeout;
        if (!fn() && canPoll)  { // ensures the function exucutes
            setTimeout(p, interval);
        }
    })();
}

pollFunc(sendHeartBeat, 60000, 1000);

function sendHeartBeat(params) {
    ...
    ...
    if (receivedData) {
        // no need to execute further
        return true; // or false, change the IIFE inside condition accordingly.
    }
}