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

setTimeout(function, 60000);

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


当前回答

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

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

其他回答

在这里,我们安慰自然数字0到......n(下一个数字每60秒在控制台打印一次),使用setInterval()

var count = 0;
function abc(){
    count ++;
    console.log(count);
}
setInterval(abc,60*1000);

我看到这里没有提到,如果你需要在重复setTimeout(myFunc(myVal), 60000)上传递一个参数给你的函数;将导致在前一个调用完成之前调用函数的错误。

因此,您可以像这样传递参数

setTimeout(function () {
            myFunc(myVal);
        }, 60000)

有关更详细的信息,您可以查看JavaScript花园。

希望它能帮助到一些人。

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

使用

setInterval(function, 60000);

编辑:(如果你想在时钟启动后停止它)

脚本部分

<script>
var int=self.setInterval(function, 60000);
</script>

及HTML代码

<!-- Stop Button -->
<a href="#" onclick="window.clearInterval(int);return false;">Stop</a>

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