Wait until setInterval() is done

后端 未结 4 865
走了就别回头了
走了就别回头了 2020-12-16 12:45

I would like to add a small dice rolling effect to my Javascript code. I think a good ways is to use the setInterval() method. My idea was following code (just

4条回答
  •  一向
    一向 (楼主)
    2020-12-16 12:55

    UPDATE on TheifMaster's Answer:

    You can now use Promises

    Like callbacks you can use Promises to pass a function that is called when the program is done running, if you use reject you can also handle errors with Promises.

    function rollDice() {
      return new Promise((resolve, reject) => {
        const dice = document.getElementById("dice")
    
        let i = Math.floor((Math.random() * 25) + 5)
    
        const intervalId = setInterval(() => {
          const diceValue = Math.floor((Math.random() * 6) + 1)
    
          dice.src = `./images/dice/dice${diceValue}.png`
    
          if (--i < 1) {
            clearInterval(intervalId)
            resolve(diceValue)
          }
        }, 50)
      })
    }
    

    Then use it like this:

    rollDice().then(value => alert(`Dice rolled: ${value}`))
    

提交回复
热议问题