【发布时间】:2016-11-24 16:04:51
【问题描述】:
在下面的 jQuery 代码中,计数器以开始按钮启动并使用停止按钮停止。代码按预期工作,但是如果您多次单击开始按钮,那么增量速度会增加,我更想知道为什么会发生这种情况而不是修复,但这也很好。
<style>
#count{
box-sizing:border-box;
height: 100px;
width: 100px;
padding: 30px;
margin-bottom: 30px;
background-color: red;
font-size: 40px;
color: white; }
</style>
HTML
<div id="count"></div>
<button id="stop">Stop Counter</button>
<button id="start">Start Counter</button>
jQuery
<script>
var eID;
var $t = $('#count');
$t.text('0');
$('#start').click(function() {
eID = window.setInterval(function(){
curr = $t.text();
new_count = parseInt(curr) + 1;
$t.text(new_count + '');
},1000);
console.log(eID);
});
$('#stop').click(function (){
window.clearTimeout(eID)
});
</script>
谢谢
bt
【问题讨论】:
-
原因是每次点击都会启动另一个间隔实例。
-
还要注意
clearTimeout()不是setInterval()的反面——clearInterval()是。
标签: jquery