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

setTimeout(function, 60000);

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


当前回答

您可以简单地在函数末尾调用setTimeout。这将再次将其添加到事件队列中。您可以使用任何类型的逻辑来改变延迟值。例如,

function multiStep() {
  // do some work here
  blah_blah_whatever();
  var newtime = 60000;
  if (!requestStop) {
    setTimeout(multiStep, newtime);
  }
}

其他回答

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

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

更好地使用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.
    }
}

使用窗口。setInterval(函数、时间)。

Call a Javascript function every 2 second continuously for 10 second. var intervalPromise; $scope.startTimer = function(fn, delay, timeoutTime) { intervalPromise = $interval(function() { fn(); var currentTime = new Date().getTime() - $scope.startTime; if (currentTime > timeoutTime){ $interval.cancel(intervalPromise); } }, delay); }; $scope.startTimer(hello, 2000, 10000); hello(){ console.log("hello"); }

函数随机(数){ return Math.floor(Math.random() * (number+1)); } setInterval(() => { const rndCol = ' rgb(' +随机(255 ) + ',' + 随机(255 ) + ',' + 随机(255 ) + ')';// rgb值(0 - 255 0 - 255 0 - 255) document.body.style.backgroundColor = rndCol; }, 1000); < script src = " . js " > < /脚本> 它每1秒改变背景颜色(在JS中写为1000)