i've try to built stopwatch from freecodecamp tutorial, when i add feature to reset it i realize that i should click twice to play after reset it.. any answer or solution for it? btw its my first question and i'm absolute beginner.
i've tried to find solution from other question and chatGPT but does not work.. here's my code :
start.addEventListener('click', function() {
if (timerStatus === 'stopped') {
timerInterval = window.setInterval(stopwatch, 1000);
document.getElementById('start').innerHTML = `<i id="play">Pause</i>`;
timerStatus = 'started';
} else if (timerStatus === 'started') {
window.clearInterval(timerInterval);
document.getElementById('start').innerHTML = `<i id="play">Play</i>`;
timerStatus = 'paused';
} else if (timerStatus === 'paused') {
timerInterval = window.setInterval(stopwatch, 1000);
document.getElementById('start').innerHTML = `<i id="play">Pause</i>`;
timerStatus = 'started';
}
});
reset.addEventListener('click', function() {
window.clearInterval(timerInterval);
seconds = 0;
minutes = 0;
hours = 0;
document.getElementById('start').innerHTML = `<i id="play" >Play</i>`;
document.getElementById('timer').innerHTML = "00:00:00"
})
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css" />
<div class="container">
<div id="timer">
00:00:00
</div>
<div class="buttons">
<button id="start">
<i class="fa-solid fa-play" id="play">Play</i>
</button>
<button id="reset">
<i class="fa-solid fa-arrow-rotate-left" id="reset2">Reset</i>
</button>
</div>
</div>
The problem is simply because you're not resetting
timerStatusback tostoppedwhen you click the Reset button.Also note there's a few improvements you can make, such as selecting the elements in the DOM once and storing them in variables you can re-use, setting
textContentto just update the node instead ofinnerHTMLto re-write the entire HTML, and placing repeated logic in to reusable functions.Below is a simplified working example, as the content of the
stopWatchmethod wasn't provided in the question.