如何在JavaScript中停止时钟?点击停止按钮后时钟仍运行
解决JavaScript时钟无法停止的问题
问题根源
你的代码里,<script>标签写在<button id="stopbutton">之前,当脚本执行时,浏览器还没渲染出这个按钮元素,导致document.querySelector('#stopbutton')返回null。后续给stopButton绑定点击事件的代码相当于给null加监听,完全不起作用,所以点击停止按钮时clearInterval(clockInterval)根本不会执行,时钟自然停不下来。
修复方案
有两种简单的修复方式:
方案1:将脚本移到按钮之后
把<script>标签放到<button>元素的后面,确保浏览器先渲染按钮,再执行脚本查找元素:
<!DOCTYPE html> <html> <head> <h1> Welcome to the clock. Press the stop button to stop the clock </h1> <h2> This clock goes for 24 hours at 100 miloseconds</h2> <div id="clock"></div> <button id="stopbutton">Stop</button> <script> const clockElement = document.querySelector('#clock'); const stopButton = document.querySelector('#stopbutton'); let clockInterval = setInterval(() => { let currentTime = new Date(); clockElement.innerHTML = currentTime.toLocaleTimeString(); }, 100); stopButton.addEventListener('click', () => { clearInterval(clockInterval); }); </script> </head> </html>
方案2:监听DOM加载完成事件
把脚本代码包裹在DOMContentLoaded事件回调里,确保DOM全部加载完成后再执行元素查找和事件绑定:
<!DOCTYPE html> <html> <head> <h1> Welcome to the clock. Press the stop button to stop the clock </h1> <h2> This clock goes for 24 hours at 100 miloseconds</h2> <div id="clock"></div> <script> document.addEventListener('DOMContentLoaded', () => { const clockElement = document.querySelector('#clock'); const stopButton = document.querySelector('#stopbutton'); let clockInterval = setInterval(() => { let currentTime = new Date(); clockElement.innerHTML = currentTime.toLocaleTimeString(); }, 100); stopButton.addEventListener('click', () => { clearInterval(clockInterval); }); }); </script> <button id="stopbutton">Stop</button> </head> </html>
内容的提问来源于stack exchange,提问作者Renato Vilchez
相关产品推荐
相关产品推荐

