2

所以我有这个计数器,它需要每 60 秒将一个数字增加 75。我在下面的代码可以做到这一点,但是由于四舍五入,一些数字比其他数字停留的时间更长,并且一些数字被跳过了。

我宁愿让这个平滑/均匀地计数以获得相同的最终结果。我知道我需要以某种方式计算setInterval计时器编号,但我不确定要得到什么。

(function(){
    //Numbers
    var num = 0;
    var perMinute = 75;
    var perSecond = perMinute / 60;

    //Element selection
    var count = document.getElementById("count");

    function update(){

        //Add the per-second value to the total
        num += perSecond;

        //Display the count rounded without a decimal
        count.innerHTML = Math.round(num);
    }

    //Run the update function once every second
    setInterval(update, 1000);
})();

工作示例:http: //jsfiddle.net/ChrisMBarr/9atym/1/

4

2 回答 2

2

永远不要依赖TimeoutInterval准确。相反,保存“开始时间”并将其与当前时间进行比较。

(function() {
    var start = new Date().getTime(),
        perMinute = 75,
        perMS = perMinute/60000,
        count = document.getElementById('count');
    function update() {
        var elapsed = new Date().getTime()-start;
        count.innerHTML = Math.round(elapsed*perMS);
    }
    setInterval(update,1000);
})();

请注意,您可以调整1000以改变计数器的“平滑度”(对于较大的 值更重要perMinute),并且它将始终完美地工作,以在分辨率的过冲范围内。

于 2013-02-28T01:34:04.293 回答
1

移动你的四舍五入似乎可以解决这个问题(编辑:不,它没有。请参阅我在下面放置的更好修复的 jsfiddle 示例)。

(function(){
//Numbers
var num = 0;
var perMinute = 75;
var perSecond = perMinute / 60;

//Element selection
var count = document.getElementById("count");

function update(){

    //Add the per-second value to the total
    num += Math.round(perSecond);

    //Display the count rounded without a decimal
    count.innerHTML = num;
}

//Run the update function once every second
setInterval(update, 1000/perSecond);
})();

编辑:适当的修复 - http://jsfiddle.net/4y2y9/1/

于 2013-02-28T01:38:07.250 回答