本文介绍了为什么clearInterval只工作一次?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个例子:
<p id="test"></p>
<button onClick="clearInterval(myVar)">Stop time!</button>
<button onClick="setInterval(myTimer, 1000)">Start time!</button>
<script>
var myVar = setInterval(myTimer, 1000);
function myTimer() {
var d = new Date();
document.getElementById('test').innerHTML = d.toLocaleTimeString();
}
</script>
当我单击停止时间!"时第一次可以正常运行,但是在我单击开始时间!"之后我不能再停止计时器了.为什么会发生这种情况以及如何解决呢?
When I click "Stop time!" for the first time it works as it should, but after I click "Start time!" I cannot stop timer anymore. Why exactly is this happening and how to fix this?
谢谢.
推荐答案
查看此代码
<button onClick="setInterval(myTimer, 1000)">Start time!</button>
它不起作用,因为您没有将新计时器设置为变量.它不知道应该在此处设置新值.
It does not work because you do not set the new timer to the variable. It does not know the new value should be set there.
不喜欢内联代码,但是可以使用
Not a fan of inline code, but this would work
<button onClick="myVar = setInterval(myTimer, 1000)">Start time!</button>
更好的设计应该是这样的:
A better design would be something like this:
(function() {
var timer;
function myTimer() {
var d = new Date();
document.getElementById('test').innerHTML = d.toLocaleTimeString();
}
function startTimer() {
stopTimer(); //make sure timer is not already running
timer = setInterval(myTimer, 1000); //start new timer
}
function stopTimer() {
if (timer) clearInterval(timer);
timer = null;
}
document.getElementById("stop").addEventListener("click", stopTimer);
document.getElementById("start").addEventListener("click", startTimer);
startTimer();
}());
<p id="test"></p>
<button id="stop">Stop time!</button>
<button id="start">Start time!</button>
这篇关于为什么clearInterval只工作一次?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!