Javascript 计数器加速
我不明白为什么每次单击“开始”时,该脚本都会导致计数器加速。我需要插入什么来防止这种情况发生Javascript 计数器加速,javascript,jquery,Javascript,Jquery,我不明白为什么每次单击“开始”时,该脚本都会导致计数器加速。我需要插入什么来防止这种情况发生 var count = 1; var counting = function () { timer = setInterval(function () { $('#numbers').html(count); count++; }, 1000); function counting() {}; } $("#start").click(countin
var count = 1;
var counting = function () {
timer = setInterval(function () {
$('#numbers').html(count);
count++;
}, 1000);
function counting() {};
}
$("#start").click(counting);
$('#stop').click(function () {
clearTimeout(timer);
});
$('#reset').click(function () {
count = 0;
$('#numbers').html(count);
});
您需要将
设置间隔
与清除间隔
匹配,而不是清除超时
如果计时器已经启动,您还需要防止对计数的额外调用,例如,将$('#start').prop('disabled',true)
调用放入计数中
或者,只需确保在调用timer=setInterval(…)
之前立即调用clearInterval(timer)
,因为每次单击“开始”时,它都会调用创建间隔的函数。再次调用setInterval函数不会停止上一个间隔
一个快速的解决方案是在setInterval(…)
之前调用clearInterval(timer)
,如下所示:
var timer;
var counting = function() {
clearInterval( timer );
timer = setInterval( function() {
$('#numbers').html( count );
count++;
}, 1000 );
}
请注意,我事先声明了timer
,因为第一次单击“开始”会生成一个错误,例如timer未定义,除非清除现有的间隔,否则每次单击“开始”都会创建一个新的间隔。