在骰子掷骰事件监听器中,如何在新骰子图像加载完毕后延迟警报?

时间:2019-04-09 19:05:28

标签: javascript addeventlistener

我正在练习Javascript,并创建了一个带有两个骰子和数字1-12的骰子骰子。掷骰子时,与掷骰子总数匹配的数字(1-12)会显示一个红色的虚线边框,当您单击它时,它将变成灰色。

我的图片来源是“ die_1”到“ die_6”,我只是随机生成一个1-6,然后将其放入“ die_”字符串中以更改图片的src。

现在,如果您输入的数字已经是灰色,则会弹出一个警报,提示“再次滚动”。

我的问题是:在我当前的实现中,警报在骰子的图像更改之前弹出。一旦我单击“确定”,骰子就会更改以显示滚动的数字。有没有办法将警报延迟到骰子的图像改变之前?

var diePicture1 = document.getElementById("die1");
var diePicture2 = document.getElementById("die2");
const NUMBERBUTTONS = document.querySelectorAll(".number-button");
buttonRoll = document.getElementById('roll');

/* Gets the values of the dice and adds them */

function totalDice(){
  var die1Value = parseInt(diePicture1.src.substring(diePicture1.src.length - 5,diePicture1.src.length-4));

  var die2Value = parseInt(diePicture2.src.substring(diePicture2.src.length - 5,diePicture1.src.length-4));

  var result = die1Value + die2Value;

  return result;

}

buttonRoll.addEventListener('click', function(){

/*Randomly generates two numbers 1-6
then changes the img src to match */


  var dieNumber1 = Math.floor(Math.random()*6) +1;
  var dieNumber2 = Math.floor(Math.random()*6) +1;
  diePicture1.src = "die_" + dieNumber1 +".png";
  diePicture2.src = "die_" + dieNumber2 +".png";
  var total = totalDice();

/*Checks to see if there are any numbers leftover
with a red border. If so, clears them */

  currentNumber = NUMBERBUTTONS[total-1];
  for (i=0; i<12; i++) {
    if (NUMBERBUTTONS[i].style.border = "2px dashed red"){
      NUMBERBUTTONS[i].style.border = "";
    }
  }

/*Gives red border if the color is not gray already */


  if (currentNumber.style.background != "gray") {
    currentNumber.style.border = "2px dashed red";
  } else {

/*this is what is popping up before the dice images have had a chance 
to change on screen */

    alert("Roll Again");
  }

}, false);

/*Turns number gray when clicked on IF border is red */
document.addEventListener('click',function(e){
  if (e.target.style.border === "2px dashed red"){
    e.target.style.border = "";
    e.target.style.background = "gray";
  }


},false);

3 个答案:

答案 0 :(得分:1)

您是否尝试过添加setTimeOut方法?将超时设置为在骰子的图像更改后弹出警报。

答案 1 :(得分:1)

非常容易。 设置超时功能有两个参数,您要运行的参数和运行它的时间,因此可以将警报放入方法中并设置超时。

点击链接以获取更多详细信息 https://www.w3schools.com/js/js_timing.asp

答案 2 :(得分:1)

尝试使用Promises

  var dieNumber1 = Math.floor(Math.random()*6) +1;
  var dieNumber2 = Math.floor(Math.random()*6) +1;
  diePicture1.src = "die_" + dieNumber1 +".png";
  diePicture2.src = "die_" + dieNumber2 +".png";
  var total = totalDice();

  var promise1 = new Promise((resolve, reject) => {
    diePicture1.addEventListener('load', () => {
      resolve();
    })
  })

  var promise2 = new Promise((resolve, reject) => {
    diePicture2.addEventListener('load', () => {
      resolve();
    })
  })
...

Promise.all([promise1, promise2]).then(() => {alert('Roll Again')})

在这里,直到两个图像都加载后才会发出警报。