How to wait until setInterval is done with JavaScript?

Sometimes, we want to wait until setInterval is done with JavaScript.

In this article, we’ll look at how to wait until setInterval is done with JavaScript.

How to wait until setInterval is done with JavaScript?

To wait until setInterval is done with JavaScript, we can call setInterval in a promise.

For instance, we write:

const rollDice = () => {
  return new Promise((resolve, reject) => {
    let numberOfRollsLeft = 5
    const intervalId = setInterval(() => {
      const diceValue = Math.floor(Math.random() * 6 + 1);
      numberOfRollsLeft--
      if (numberOfRollsLeft === 0) {
        clearInterval(intervalId);
        resolve(diceValue);
      }
    }, 50);
  });
}

const roll = async () => {
  const val = await rollDice()
  console.log(val)
}
roll()

We define rollDice which returns a promise.

We create the promise with the Promise constructor with a callback that calls setInterval with a callback to draw a random number.

If numberOfRollsLeft is 0, then we call clearInterval to stop the timer and call resolve with the diceValue to return that as the resolved value.

Next, we call rollDice in the roll function and use await to get the resolved promise value.

Conclusion

To wait until setInterval is done with JavaScript, we can call setInterval in a promise.