简体   繁体   English

如何在 JS 中添加事件侦听器冷却时间(禁用然后重新启用事件单击)

[英]How to add eventlistener cooldown (disable then re-enable event click) in JS

I am building a rock paper scissors game in JS.我正在用 JS 构建一个石头剪刀布游戏。 The user chooses their input of rock/paper/scissors by clicking on their respective divs via element.addEventListener('click', ...) The user plays vs the computer.用户通过 element.addEventListener('click', ...) 点击他们各自的 div 来选择他们输入的石头/纸/剪刀。用户对着电脑玩。 The results display on screen for a 3 seconds and then the screen resets.结果在屏幕上显示 3 秒钟,然后屏幕重置。

Currently, the divs are still clickable while the results are being shown, which interrupts the result-showing process.目前,显示结果时仍然可以点击div,这会中断结果显示过程。

I would like to make it so that IF you try to click a div to input rock/paper/scissors during the result showing process (within 3 seconds after clicking), the divs are disabled such that clicking them does nothing.我想这样做,如果您在结果显示过程中(单击后 3 秒内)尝试单击 div 以输入石头/纸/剪刀,则 div 将被禁用,因此单击它们不会执行任何操作。 Then once the 3 seconds are over, I want to re-enable the divs so that clicking them works again.然后一旦 3 秒结束,我想重新启用 div,以便再次单击它们。

In simple terms, I want to add a cool-down to my div.addEventListener('click', ...)简单来说,我想给我的 div.addEventListener('click', ...) 添加一个冷却

var rock = document.getElementById("rock");

function layoutReset(){
   *reset the layout*
   ***re-enable rock.addEventListener('click')***
}
function game(){
   *play game*
   *show results*
   ***disable rock.addEventListener('click');***
   setTimeout(layoutReset(), 3000);   

}

rock.addEventListener('click', function{
   game();

})

I found a solution.我找到了解决方案。 Create a boolean for whether or not the transition is taking place.创建一个布尔值来确定是否正在发生转换。

var transitioning = false;

function layoutreset(){
   *reset stuff*
   transitioning = false;
}
function game(){
   *play game*
   *show results*
   transitioning=true
   setTimeout(layoutReset(), 3000);   
}


div.onclick = function(){
   if(transitioning=false){
      game();
   };
}

Now the code checks if its transitioning, if it is, it doesn't do anything.现在代码检查它是否正在转换,如果是,它什么都不做。 If it isnt, it will change transitioning to false, then back to true after a 3 second delay.如果不是,它将转变为 false,然后在 3 秒延迟后恢复为 true。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM