我正在尝试制作秒表,但 setTimeout 没有按预期工作。当我按下状态按钮时,只有
count
变量发生变化,而不是根据 setTimeout
函数发生变化。这是我的 JavaScript 代码
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);
}
}
这只是函数定义,不是函数调用。 要使用您的代码,请尝试这样做。
(函数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);
}
})()