使用setTimeout()可以在指定的时间启动一个函数:
setTimeout(function, 60000);
但是如果我想多次启动这个函数呢?每当一个时间间隔过去时,我都希望执行函数(假设每60秒执行一次)。
使用setTimeout()可以在指定的时间启动一个函数:
setTimeout(function, 60000);
但是如果我想多次启动这个函数呢?每当一个时间间隔过去时,我都希望执行函数(假设每60秒执行一次)。
当前回答
我倾向于调用包含循环函数的函数,该循环函数定期对自身调用setTimeout。
函数计时器(间隔 = 1000) { 函数循环(计数 = 1) { 控制台.log(计数); setTimeout(loop, interval, ++count); } 循环(); } 计时器();
其他回答
一个订阅setInterval()并使用clearInterval()来停止永久循环的好例子:
function myTimer() {
}
var timer = setInterval(myTimer, 5000);
调用这一行来停止循环:
clearInterval(timer);
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"); }
在这里,我们安慰自然数字0到......n(下一个数字每60秒在控制台打印一次),使用setInterval()
var count = 0;
function abc(){
count ++;
console.log(count);
}
setInterval(abc,60*1000);
使用窗口。setInterval(函数、时间)。
我看到这里没有提到,如果你需要在重复setTimeout(myFunc(myVal), 60000)上传递一个参数给你的函数;将导致在前一个调用完成之前调用函数的错误。
因此,您可以像这样传递参数
setTimeout(function () {
myFunc(myVal);
}, 60000)
有关更详细的信息,您可以查看JavaScript花园。
希望它能帮助到一些人。