使用setTimeout()可以在指定的时间启动一个函数:
setTimeout(function, 60000);
但是如果我想多次启动这个函数呢?每当一个时间间隔过去时,我都希望执行函数(假设每60秒执行一次)。
使用setTimeout()可以在指定的时间启动一个函数:
setTimeout(function, 60000);
但是如果我想多次启动这个函数呢?每当一个时间间隔过去时,我都希望执行函数(假设每60秒执行一次)。
当前回答
在这里,我们安慰自然数字0到......n(下一个数字每60秒在控制台打印一次),使用setInterval()
var count = 0;
function abc(){
count ++;
console.log(count);
}
setInterval(abc,60*1000);
其他回答
如果你不关心计时器内的代码是否会比你的间隔时间长,请使用setInterval():
setInterval(function, delay)
反复触发作为第一个参数传入的函数。
一个更好的方法是使用setTimeout和一个自动执行的匿名函数:
(function(){
// do some stuff
setTimeout(arguments.callee, 60000);
})();
这保证了在执行代码之前不会进行下一次调用。我使用了论点。本例中的Callee作为函数引用。给函数命名并在setTimeout中调用是一种更好的方式因为参数。Callee在ecmascript 5中已弃用。
函数随机(数){ 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)
一个订阅setInterval()并使用clearInterval()来停止永久循环的好例子:
function myTimer() {
}
var timer = setInterval(myTimer, 5000);
调用这一行来停止循环:
clearInterval(timer);
使用窗口。setInterval(函数、时间)。
// example:
// checkEach(1000, () => {
// if(!canIDoWorkNow()) {
// return true // try again after 1 second
// }
//
// doWork()
// })
export function checkEach(milliseconds, fn) {
const timer = setInterval(
() => {
try {
const retry = fn()
if (retry !== true) {
clearInterval(timer)
}
} catch (e) {
clearInterval(timer)
throw e
}
},
milliseconds
)
}