[英]How can I temporarily disable a button or 'click' event in javascript?
I have a javascript codum playing rock paper scissors with the computer when I click on one of the options, but after selecting one of the rock-paper-scissors I want the button or click event to be disabled for 2 seconds, let me explain the event more clearly;当我单击其中一个选项时,我有一个 javascript codum 在用电脑玩石头剪刀布,但是在选择其中一个石头剪刀布之后,我希望按钮或点击事件被禁用 2 秒钟,让我解释一下事件更清晰; I clicked the button of one of the three of Rock-Paper-Scissors and the 2 second animation started and while this animation is being made I shouldn't press a new button, that click event won't work for 2 seconds.
我点击了三个石头剪刀布之一的按钮,然后 2 秒 animation 开始了,当这个 animation 正在制作时,我不应该按下新按钮,该点击事件不会在 2 秒内起作用。
// Code of click event (it's inner of options.forEach)
const playMatch = () => {
const options = document.querySelectorAll(".options button");
const playerHand = document.querySelector(".player-hand");
const computerHand = document.querySelector(".computer-hand");
const hands = document.querySelectorAll(".hands img");
hands.forEach(hand => {
hand.addEventListener('animationend', function () {
this.style.animation = '';
})
})
//Computer Options
const computerOptions = ["rock", "paper", "scissors"];
options.forEach(option => {
option.addEventListener("click", function () {
//Computer Choice
const computerNumber = Math.floor(Math.random() * 3);
const computerChoice = computerOptions[computerNumber];
setTimeout(() => {
compareHands(this.textContent, computerChoice);
playerHand.src = `./assets/${this.textContent}.png`;
computerHand.src = `./assets/${computerChoice}.png`;
}, 2000);
// Animation
playerHand.style.animation = "shakePlayer 2s ease";
computerHand.style.animation = "shakeComputer 2s ease";
});
});
};
I would wrap my function inside something like this我会把我的 function 包裹在这样的东西里面
const throttle = (func, wait = 2000) => {
let timer = null;
return function(...args) {
if (timer === null) {
timer = setTimeout(() => {
func.apply(this, args);
timer = null;
}, wait);
}
};
};
What this does is that it would prevent the function from responding until the wait time is elapsed.这样做是为了防止 function 在等待时间过去之前做出响应。
You can put your clickable items (buttons) inside a <form>
element (or any parent element, really) and do this:您可以将可点击项目(按钮)放在
<form>
元素(或任何父元素,实际上)内,然后执行以下操作:
const form = document.querySelector('form') // or '.my-form' or '#my-form-id' etc.
const btn = document.querySelector('#the-button')
const disableForm = (selector, state) => {
let elements = document.querySelector(selector).elements
for (let cnt = 0; cnt < elements.length; cnt++) {
elements[cnt].disabled = state
}
}
btn.addEventlistener('click', () => {
disableForm(form, true)
// do other stuff
// Remove form lock after 2s:
setTimeout(() => { disableForm(form, false) }, 2000)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.