I am trying to make stopwatch but setTimeout is not working as intended.when I press state button then only count
variable changes and not according to setTimeout
function. Here’s my javascript code
const hr_button = document.querySelector("#hr");
const min_button = document.querySelector("#min");
const sec_button = document.querySelector("#sec");
const state_button = document.querySelector("#state");
const reset_button = document.querySelector("#reset");
const milli_button = document.querySelector("#milli");
let isPause = true;
let count = 0;
let intervalId;
state_button.addEventListener("click", ()=>{
if (isPause){
state_button.innerHTML = "Start";
reset_button.style.color = "white";
stopWatch();
}
else{
state_button.innerHTML = "Stop";
reset_button.style.color = "gray";
}
isPause = !isPause;
});
function stopWatch() {
if (!isPause){
console.log("Hello");
count+=10;
if(count ==1000){
parseInt(sec_button.innerHTML) +=1;
count = 0;
}
if(parseInt(sec_button.innerHTML) == 60){
parseInt(min_button.innerHTML) +=1;
sec_button.innerHTML ="00";
}
if(min_button.innerHTML == 60){
hr_button +=1;
min_button.innerHTML="00";
}
milli_button.innerHTML = count;
setTimeout(stopWatch,1000);
}
}
2
Answers
That’s only function definition, not function call.
To use your code, please try as this.
(function stopWatch() {
if (isPause){
In the click handler, the pause gets inverted. Thus, at the next stopWatch() execution, after 1000ms, nothing will happen there.
You need to rework your logic.