我试图一次每秒运行X次函数。
我试图在一个循环中设置setTimeout,但是它不是每秒运行一次,而是等待一秒钟然后运行5次。
Press.advance = function(distance) {
for (var i = 0; i < distance; i++) {
setTimeout(() => {
console.log('advancing') //want it to do this once per second
}, 1000)
}
}
如何使它每秒运行distance
次?
答案 0 :(得分:0)
您可以使用setInterval
代替setTimeout
。像这样:
var interval = null; // create a holder for the interval id
var counter = 0; // counter for checking if `distance` has been reached
var Press = {
advance: function(distance) {
interval = interval || window.setInterval(() => {
if (distance == counter++) {
console.log('cleared');
window.clearInterval(interval);
} else {
console.log('advancing') //want it to do this once per second
}
}, 1000);
}
}
Press.advance(2);