[英]JavaScript ClearInterval button doesn't stop
I've reviewed the other clearInterval posts here for a clue as to why my code isn't functioning as intended.我已经在这里查看了其他 clearInterval 帖子,以了解为什么我的代码没有按预期运行。 Despite my best efforts, I still can't get clearInterval to stop my count.
尽管我尽了最大的努力,我仍然无法得到 clearInterval 来停止我的计数。
I'm trying to do something simple: have a count, increase by one until the stop button is pushed.我正在尝试做一些简单的事情:计数,加一直到按下停止按钮。
I have tried different, and incorrect variables, but I cannot find a working solution.我尝试了不同且不正确的变量,但找不到有效的解决方案。
<p>Count Up:</p>
<p id="count">1</p>
<button onclick="clearInterval(current)">Stop</button>
<script>
var current = 1;
function animateValue(id) {
var obj = document.getElementById(id);
var current = parseInt(obj.innerHTML);
setInterval(function () {
current++;
obj.innerHTML = current;
}, 1000);
}
animateValue("count");
</script>
Store the value returned by setInterval
in a variable and pass that as the parameter to clearInterval
instead of counter
:将
setInterval
返回的值存储在一个变量中,并将其作为参数传递给clearInterval
而不是counter
:
<p>Count Up:</p> <p id="count">1</p> <button onclick="clearInterval(interval)">Stop</button> <script> var interval; var current = 1; function animateValue(id) { var obj = document.getElementById(id); var current = parseInt(obj.innerHTML); interval = setInterval(function () { current++; obj.innerHTML = current; }, 1000); } animateValue("count"); </script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.