Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/435.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 计数器加速_Javascript_Jquery - Fatal编程技术网

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未定义

,除非清除现有的间隔,否则每次单击“开始”都会创建一个新的间隔。