使用setTimeout()可以在指定的时间启动一个函数:
setTimeout(function, 60000);
但是如果我想多次启动这个函数呢?每当一个时间间隔过去时,我都希望执行函数(假设每60秒执行一次)。
使用setTimeout()可以在指定的时间启动一个函数:
setTimeout(function, 60000);
但是如果我想多次启动这个函数呢?每当一个时间间隔过去时,我都希望执行函数(假设每60秒执行一次)。
当前回答
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"); }
其他回答
您可以简单地在函数末尾调用setTimeout。这将再次将其添加到事件队列中。您可以使用任何类型的逻辑来改变延迟值。例如,
function multiStep() {
// do some work here
blah_blah_whatever();
var newtime = 60000;
if (!requestStop) {
setTimeout(multiStep, newtime);
}
}
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"); }
有两种方法叫-
setInterval(function (){functionName();}, 60000); setInterval (functionName, 60000);
以上函数将每60秒调用一次。
在这里,我们安慰自然数字0到......n(下一个数字每60秒在控制台打印一次),使用setInterval()
var count = 0;
function abc(){
count ++;
console.log(count);
}
setInterval(abc,60*1000);
函数随机(数){ 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)