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

时间:2015-03-11 18:16:21

标签: javascript math setinterval increment

我试图在一定的持续时间(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;
}

这有点奏效,但不尊重持续时间。即如果您将号码从1000增加到1000000000,则他们都会花费不同的时间来到达目的地号码。

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

2 个答案:

答案 0 :(得分:1)

正如@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);

答案 1 :(得分:1)

我和你的小提琴一起玩,发现延迟需要更高。在8ms或16ms时,它足以准确处理一秒钟,但不够精确,无法处理半秒钟。从实验来看,似乎64ms的延迟足够小,看起来像是在顺利递增,但大到足以产生准确的效果。

不同之处在于,当前数字是根据流程计算的,而不是直接操作的。

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用例,这应该足够准确。