在设定时间内从零增加到数字

Increment from zero to number in a set time

我正在尝试在特定持续时间(1000 毫秒、5000 毫秒等)内从 0 递增到一个数字(可以是 2000 到 12345600000 之间的任何数字)。我创建了以下内容:

http://jsfiddle.net/fmpeyton/c9u2sky8/

var counterElement = $(".lg-number");
var counterTotal = parseInt(counterElement.text()/*.replace(/,/g, "")*/);
var duration = 1000;
var animationInterval = duration/counterTotal;

counterElement.text("0");
var numberIncrementer = setInterval(function(){
    var currentCounterNumber = parseInt(counterElement.text()/*.replace(/,/g, "")*/);
    
    if (currentCounterNumber < counterTotal){
        currentCounterNumber += Math.ceil(counterTotal/duration);
    
        // convert number back to comma format
        // currentCounterNumber = addCommas(currentCounterNumber);
        
        counterElement.text(currentCounterNumber);
    } else {
        counterElement.text(counterTotal);
        clearInterval(numberIncrementer);
    }
    
    console.log("run incrementer");
}, animationInterval);

function addCommas(number){
    for (var i = number.length - 3; i > 0; i -= 3)
        number = number.slice(0, i) + ',' + number.slice(i);
    
    return number;
}

这有点管用,但它不考虑持续时间。 IE。如果您将号码从 1000 增加到 1000000000,它们到达目标号码所需的时间会有所不同。

如何在特定时间范围内从零递增到数字?

正如@Mouser 指出的那样,问题在于 animationInterval 不能太小(实际的最小阈值会因浏览器和平台而异)。不要改变间隔,而是改变计数器的增量:

var counterElement = $(".lg-number");
var counterTotal = parseInt(counterElement.text()/*.replace(/,/g, "")*/);
var duration = 1000;
var animationInterval = 10;
var startTime = Date.now();

counterElement.text("0");
var numberIncrementer = setInterval(function(){
    var elapsed = Date.now() - startTime;
    var currentCounterNumber = Math.ceil(elapsed / duration * counterTotal);
    if (currentCounterNumber < counterTotal){
        counterElement.text(currentCounterNumber);
    } else {
        counterElement.text(counterTotal);
        clearInterval(numberIncrementer);
    }

    console.log("run incrementer");
}, animationInterval);

我试过你的fiddle,发现延迟需要更高。在 8 毫秒或 16 毫秒时,它的精度足以处理一秒,但不足以处理半秒。从实验来看,似乎 64 毫秒的延迟小到看起来像是在平滑地递增,但又大到足以产生准确的效果。

不同的是,当前的数字是根据流程计算出来的,而不是直接操纵的。

var counterElement = $(".lg-number");
var counterTotal = parseInt(counterElement.data('total'));
var interval = 0;
var duration = parseInt(counterElement.data('duration'));;
var delay = 64

var numberIncrementer = setInterval(function(){
    var currentCounterNumber = 0;

    interval += delay;

    if (interval <= duration){
        var progress = interval / duration;
        currentCounterNumber = Math.round(progress * counterTotal);
    } else {
        currentCounterNumber = counterTotal
        clearInterval(numberIncrementer);
    }

    counterElement.text(currentCounterNumber);
}, delay);

http://jsfiddle.net/c9u2sky8/5/

还有:Javascript timers are not perfectly accurate。但这对于 UI 个用例应该足够准确。