X每秒运行一次功能

时间:2018-08-08 18:13:10

标签: javascript

我试图一次每秒运行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次?

1 个答案:

答案 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);