1

I'm attempting to run a function X number of times, once per second.

I've tried to setTimeout within a loop, but instead of running once per second, it waits one second then runs 5 times.

Press.advance = function(distance) {

  for (var i = 0; i < distance; i++) {

    setTimeout(() => {
      console.log('advancing') //want it to do this once per second
    }, 1000)

  }
}

How can I make it run once per second for distance number of times?

chuckieDub
  • 1,767
  • 9
  • 27
  • 46

1 Answers1

0

You could use setInterval instead of setTimeout. Like this:

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);
lealceldeiro
  • 14,342
  • 6
  • 49
  • 80