Count animation from number A to B

后端 未结 8 984
一个人的身影
一个人的身影 2020-11-30 22:18

I am updating a numeric value inside an element by doing intervalled ajax requests.

To make the whole thing a bit more alive,

8条回答
  •  伪装坚强ぢ
    2020-11-30 22:40

    This works well. However, I needed to use a comma within the number. Below is the updated code which checks for commas. Hope someone finds this useful if they stumble across this post.

    function animateValue(id, start, end, duration) {
    
        // check for commas
        var isComma = /[0-9]+,[0-9]+/.test(end); 
        end = end.replace(/,/g, '');
    
        // assumes integer values for start and end
    
        var obj = document.getElementById(id);
        var range = end - start;
        // no timer shorter than 50ms (not really visible any way)
        var minTimer = 50;
        // calc step time to show all interediate values
        var stepTime = Math.abs(Math.floor(duration / range));
    
        // never go below minTimer
        stepTime = Math.max(stepTime, minTimer);
    
        // get current time and calculate desired end time
        var startTime = new Date().getTime();
        var endTime = startTime + duration;
        var timer;
    
        function run() {
            var now = new Date().getTime();
            var remaining = Math.max((endTime - now) / duration, 0);
            var value = Math.round(end - (remaining * range));
            obj.innerHTML = value;
            if (value == end) {
                clearInterval(timer);
            }
            // Preserve commas if input had commas
            if (isComma) {
                while (/(\d+)(\d{3})/.test(value.toString())) {
                    value = value.toString().replace(/(\d+)(\d{3})/, '$1'+','+'$2');
                }
            }
        }
    
        var timer = setInterval(run, stepTime);
        run();
    }
    
    animateValue("value", 100, 25, 2000); 
    

提交回复
热议问题