1

I have simple function like this:

let test = () => {
    let positionsArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
    console.log(
      positionsArray[Math.floor(Math.random() * positionsArray.length + 0)]
    );
  };

How can I run it for example 5 times with a time interval of 2 seconds? I tried to do this with for loop and setInterval function, but after 5 times I couldn't stop the interval and I was calling this function infinite. Any ideas?

mdzialo
  • 17
  • 5

1 Answers1

1

Try this:

let count = 0;

const test = () => {
  let positionsArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
  console.log(
    positionsArray[Math.floor(Math.random() * positionsArray.length + 0)]
  );
  if(++count === 5) clearInterval(interval);
};

const interval = setInterval(test, 2000);
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48