[英]Pause works incorrectly. How to fix?
I have a code that should implement stopwatch.我有一个应该实现秒表的代码。 It works, but if I start stopwatch after pressed pause or reset button, then time is ticking too fast.
它有效,但如果我在按下暂停或重置按钮后启动秒表,那么时间过快了。 How can I fix it?
我该如何解决?
Resolved.解决。
Here's a trimmed down example of how one could store an interval id and then use it to clear the interval:这是一个精简的示例,说明如何存储间隔 id,然后使用它来清除间隔:
let SECONDS = 0; let intervalId; function run() { intervalId = setInterval(main, 1000) } function pause() { clearInterval(intervalId) } function reset() { clearInterval(intervalId) SECONDS = 0 update_display() } function update_display() { document.getElementById("seconds").innerText = SECONDS } function main() { SECONDS++ update_display() }
<div class="display-time"> <span id="seconds">0</span> </div> <!-- buttons start, stop and reset --> <div class="button-group"> <button id="btnRun" onclick="run()">RUN</button> <button id="btnPause" onclick="pause()">PAUSE</button> <button id="btnReset" onclick="reset()">RESET</button> </div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.