在下面的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()'的反面。 –
謝謝你。 –