Count animation from number A to B

后端 未结 8 947
一个人的身影
一个人的身影 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:45

    This is what i came up with:

    function animateVal(obj, start=0, end=100, steps=100, duration=500) {   
        start = parseFloat(start)
        end = parseFloat(end)
    
        let stepsize = (end - start) / steps
        let current = start
        var stepTime = Math.abs(Math.floor(duration / (end - start)));
        let stepspassed = 0
        let stepsneeded = (end - start) / stepsize
    
        let x = setInterval( () => {
                current += stepsize
                stepspassed++
                obj.innerHTML = Math.round(current * 1000) / 1000 
            if (stepspassed >= stepsneeded) {
                clearInterval(x)
            }
        }, stepTime)
    }   
    
    animateVal(document.getElementById("counter"), 0, 200, 300, 200)
    

提交回复
热议问题