首页 > 解决方案 > 如果满足第一个函数的条件,则停止第二个函数

问题描述

我正在构建一个简单的游戏,其中两个玩家按不同的键,按速度更快的玩家获胜。如果满足第一个函数的条件,我将尝试停止执行第二个函数。如果第一个函数的计数等于 100,我如何禁用第二个函数?

    let count = 0;
let maxCount = 50;

function player1() {

  let player1_progress = document.getElementsByClassName("player1-progress__progressbar")[0];
  console.log(player1_progress);
  window.addEventListener("keyup", function(e) {

    console.log(e.keyCode);
    //if the button is "d"
      if (e.keyCode === 68) {
          console.log(count)
          // increase count if it's less than 100
          count = count === 100 ? 100 : count + 4;
          //target progressbar width and increase it
          let newWidth = (count / maxCount) * 50 + "%";
          player1_progress.style.width = newWidth;
          player1_progress.innerHTML = count + "%"; 

      if (count=== 100) {
        console.log("player 1 is the winner!");

      /////?????????????????????????????

            }
        }
      });
      }
player1();


//player2 count

function player2() {

let count_player2 = 0;
let player2_progress = document.getElementsByClassName("player2-progress__progressbar")[0];
window.addEventListener("keyup", function(e) {

  //if the button is "d"
  if (e.keyCode === 191) {
    // increase count if it's less than 100
    count_player2 = count_player2 === 100 ? 100 : count_player2 + 4;
    //target progressbar width and increase it
    let newWidth_player2 = (count_player2  / maxCount) * 50 + "%";
    player2_progress.style.width = newWidth_player2;
    player2_progress.innerHTML = count_player2 + "%"; 

    if (count_player2=== 100) {
      console.log("player 2 is the winner!");
    }  

  }
});
}
player2();

标签: javascripthtml

解决方案


您需要任务或多线程。


推荐阅读