Javascript 一旦玩家获胜,函数将停止执行

Javascript 一旦玩家获胜,函数将停止执行,javascript,html,Javascript,Html,我试图建立一个简单的游戏,玩家点击按钮的基础上,以100%的速度。每个玩家都有一个分配给他们的按钮,取决于谁点击得更快,玩家获胜。我想做一个逻辑,如果COUNT或COUNT_PLAYER2超过100,那么玩家将赢得一个或两个,并且所有函数都停止执行。你能帮我解释一下背后的逻辑吗 let count = 0; let maxCount = 50; let player1_progress = document.getElementsByClassName("player1-progress__pr

我试图建立一个简单的游戏,玩家点击按钮的基础上,以100%的速度。每个玩家都有一个分配给他们的按钮,取决于谁点击得更快,玩家获胜。我想做一个逻辑,如果COUNT或COUNT_PLAYER2超过100,那么玩家将赢得一个或两个,并且所有函数都停止执行。你能帮我解释一下背后的逻辑吗

let count = 0;
let maxCount = 50;
let player1_progress = document.getElementsByClassName("player1-progress__progressbar")[0];
console.log(player1_progress);
window.addEventListener("keypress", function(e) {
  console.log(e.keyCode);
  //if the button is "d"
  if (e.keyCode === 100) {
    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!");
    }
  }
});

//player2 count

let count_player2 = 0;
let player2_progress = document.getElementsByClassName("player2-progress__progressbar")[0];
window.addEventListener("keypress", function(e) {
  //if the button is "d"
  if (e.keyCode === 47) {
    // 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 + "%";
    if (count_player2 === 100) {
      console.log("player 2 is the winner!");
    }
  }
});

当其中一个计数达到100时,是否尝试删除所有事件侦听器

大概是这样的:

button_a_handler = e => {
// do stuff

if (count >= 100) {
  window.removeEventListener("keypress", button_a_handler);
  window.removeEventListener("keypress", button_b_handler);
}
};

 button_b_handler = e => {
 // do stuff

 if (count >= 100) {
   window.removeEventListener("keypress", button_a_handler);
   window.removeEventListener("keypress", button_b_handler);
 }
};

if
块中添加完整的当前执行,并进行必要的检查?