I'm trying to make a simple javascript counter.
Basically, I'm getting an integer value from a user by input and I want to count descending from that value to 0.
So I coded this:
let inputCounter = document.querySelector("#input-counter");
let startBox = document.querySelector(".start-box");
let startCounter = document.querySelector("#start-counter");
let errorMessage = document.querySelector("#error-message");
let timerCircle = document.querySelector(".c100");
let timeSpan = document.querySelector(".c100 > span");
startCounter.addEventListener('click', function() {
let seconds = inputCounter.value;
if (isNaN(seconds)) {
errorMessage.textContent = "Not an integer value";
errorMessage.classList.add("active");
} else {
errorMessage.classList.remove("active");
timerCircle.style.display = "block";
startBox.style.display = "none";
timeSpan.textContent = seconds;
let timerId = setInterval(() => {
seconds -= 1;
if (seconds < 0) {
clearInterval(timerId);
}
timeSpan.textContent = seconds;
}, 1000);
}
});
<div class="container">
<div class="start-box">
<input type="text" id="input-counter" placeholder="type your value in seconds">
<button id="start-counter">Start</button>
<div id="error-message"></div>
</div>
<div class="c100 p50">
<span></span>
<div class="slice">
<div class="bar"></div>
<div class="fill"></div>
</div>
</div>
</div>
So this works fine and properly counts down from that custom entered number but the only problem here is that it goes to -1, -2, -3 and etc.
So that is why I tried determining timerId
to the setInterval
function and then checking this condition:
if(seconds < 0){
clearInterval(timerId);
}
However it does not clear the interval and still shows Negative numbers...
So what's going wrong here? How can I properly clear the interval when it comes to 0?