简体   繁体   中英

JS smooth transition between two value change

I have this variables changing constantly, from 0 to 100 this coming from an exernal SDK like this for example:

window.addEventListener({
 variable = 0; 
})

Now when this variable change and goes to another value it's too sharp for me and I want to make this exponential, for example, not 0 => 100 directly, but I want to sample the value of variable every x millisecond e make a smooth transition between the two value with the intermediate value

example: 0 => 20 => 40 => 60 => 80 => 100

how can I do?

This should do the trick:

var animationDuration = 500; //in miliseconds
var startValue = 0;
var endValue = 100;

function animateNextFrame(currentTime) {

    if (!startTime) startTime = currentTime;
    var elapsedTime = currentTime - startTime;

    if (elapsedTime < animationDuration) {

        currentValue = Math.floor((elapsedTime / animationDuration) * (endValue - startValue));

        //set your field value to currentValue here with something like document.getElemenById...

        //call the next animation frame
        window.requestAnimationFrame(animateNextFrame);

    } else {
        //set your field value to endValue here with something like document.getElemenById...
    }
}
//trigger the number animation
window.requestAnimationFrame(animateNextFrame);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM