在代码块中内置了一个计时器。现在计时器通过按钮启动/停止,但我需要它在释放空格按钮时运行,并且我需要它在按下空格按钮时停止。我已经尝试解决这个问题大约两天了,但似乎找不到解决方案。每次我尝试停止计时器时,当我释放空格按钮时,计时器都会再次启动。
let startDate; let timeoutID = 0; let time; let started = false; let timerRunOut = false; function start(){ if(!started){ startDate = new Date(); startTimer(); started = true; } } function stop(){ if(started){ clearTimeout(timeoutID); started = false; } } function startTimer () { let current = new Date(); time = (current - startDate); let timeMS = time; let ms = timeMS % 1000; timeMS = (timeMS - ms) / 1000; let seconds = timeMS % 60; timeMS = (timeMS - seconds) / 60; let mins = timeMS % 60; if(seconds < 10){ document.getElementById("seconds").innerText = "0" + seconds; }else{ document.getElementById("seconds").innerText = seconds; } if(mins > 0 && mins < 10){ document.getElementById("minutes").innerText = "0" + mins + ":"; }else if(mins > 0){ document.getElementById("minutes").innerText = mins + ":"; }else{ document.getElementById("minutes").innerText = ""; } if(ms < 10){ document.getElementById("tens").innerText = "00" + ms; } else if(ms < 100){ document.getElementById("tens").innerText = "0" + ms; }else{ document.getElementById("tens").innerText = ms; } timeoutID = setTimeout(startTimer, 0); }
我尝试添加事件侦听器并添加条件,但没有任何效果,当计时器停止时,当我释放空格按钮时,它总是会再次启动。
我找到了解决方案,我需要给 Andre 一点功劳,他帮助我解决了问题这个出来了。