I am making a click speed game that counts how many times you can click a button in 5 seconds. The problem I am having is I cannot get the timer to reset back to 5 without it counting down on its own. I am trying to make it so when you click the "restart?" button it resets the timer back to 5 and stays at 5 until the "click to start" button is clicked just how it is when you open the page for the first time.
This is one of my first projects using Javascript on my own so please forgive the bad code. lol.
const button = document.getElementById('button');
const button2 = document.getElementById('button2');
const button3 = document.getElementById('button3');
let timer = document.getElementById('safeTimerDisplay');
let clicks = 1;
const score = document.getElementById('display');
let counter = 5;
//timer button
const timerButton = button2.addEventListener('click', onclick => {
button2.style.display = 'none';
});
//button counter
const onClickButton = button.onclick = function() {
button.textContent = (`${clicks++}`)
}
//button click starts timer
$("#button2").click(function restart(timer) {
setInterval(function() {
counter--;
if (counter >= 0) {
p = document.getElementById("safeTimerDisplay");
p.innerHTML = counter;
}
if (counter === 0) {
button3.style.display = 'block';
button.disabled = true;
}
}, 1000);
clearInterval(counter);
});
//restart button
const restartButton = button3.addEventListener('click', onclick => {
button3.style.display = 'none';
//start button resdisplay
button2.style.display = 'block';
clicks = 1;
//timer reset
//counter button back to zero
button.textContent = (`${clicks++}`)
button.disabled = false;
// everything else
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="header">
<h1>Speed Test</h1>
<p id="safeTimerDisplay">5</p>
<p class="display" id="display">score:</p>
</div>
<div class="button-container">
<button class="button2" id="button2">Click to start</button>
<button class="button" id="button">1</button>
<button class="button3" id="button3">restart?</button>
</div>