问题
What do I need to add to make the button turn off if pressed 10 times in less than 1 minute but keep counting if not pressed in 1 minute?
function buttonClicked() {
if (totalCount + accCounter > 9) {
document.getElementById("btn").disabled = true;
}
}
document.getElementById('btn').onclick = function() {
upClickCounter();
buttonClicked()
}
function upClickCounter() {
const clickCounter = document.getElementById("clicker");
const totalClickCounter = document.getElementById('totalCounter');
accCounter++;
clickCounter.children[0].innerText = '+' + accCounter;
totalClickCounter.innerText = totalCount + accCounter;
}
let accCounter = 0;
let totalCount = 0;
<button id="btn">Click me</button>
<div id="clicker">
<span></span>
</div>
<div id="totalCounter"></div>
回答1:
setTimeout(countOver, 10000); //set for 10 seconds
function countOver(){
document.getElementById('btn').disabled=true
}
function buttonClicked() {
if (totalCount + accCounter > 9) {
document.getElementById("btn").disabled = true;
}
}
document.getElementById('btn').onclick = function() {
upClickCounter();
}
function upClickCounter() {
const clickCounter = document.getElementById("clicker");
const totalClickCounter = document.getElementById('totalCounter');
accCounter++;
clickCounter.children[0].innerText = '+' + accCounter;
totalClickCounter.innerText = totalCount + accCounter;
}
let accCounter = 0;
let totalCount = 0;
<button id="btn">Click me</button>
<div id="clicker">
<span></span>
</div>
<div id="totalCounter"></div>
回答2:
You need a setTimeout
. It takes in a callback function and a timer in milliseconds. I updated upClickCounter
with a line that disables the button, then a setTimeout
that will re-enable the button after 1 minute (60,000 milliseconds).
EDIT:
I think I understand what you want, and can only wonder why, but this should do what you are describing.
let accCounter = 0;
let totalCount = 0;
let lessThanOneMinute = true;
function upClickCounter(event) {
const clickCounter = document.getElementById("clicker");
const totalClickCounter = document.getElementById('totalCounter');
accCounter++;
clickCounter.children[0].innerText = '+' + accCounter;
totalClickCounter.innerText = totalCount + accCounter;
// If the click count is greater or equal to 10 and the lessThanOneMinute is still true, disable the button
if (accCounter >= 10 && lessThanOneMinute) { event.target.disabled = true; }
}
document.getElementById('btn').onclick = upClickCounter;
setTimeout(() => { lessThanOneMinute = false }, 60000); // the lessThanOneMinute variable will become false in one minute
来源:https://stackoverflow.com/questions/65830360/what-i-have-to-add-in-javascript-to-make-it-how-i-what