Sambego
5/6/2016 - 8:55 AM

Animation function

Animation function

/*
 * A simple function to animate a property of an element to a new value.
 */
const animate = function animate(element, property, value, duration) {
    const fps = 60;
    const timeout = duration / (1000 / fps);
    const startTime = new Date();
    const startValue = element[property];
    const step = function step() {
        const currentTime = new Date();
        const passedTime = currentTime.getTime() - startTime.getTime();
        const passedTimeRatio = (passedTime / duration) > 1 ? 1 : (passedTime / duration);
        const currentValue = (startValue + ((value - startValue) * passedTimeRatio));

        element[property] = currentValue;

        if (passedTime < duration) {
            window.setTimeout(() => {
                window.requestAnimationFrame(step);
            }, timeout);
        }
    };

    window.requestAnimationFrame(step);
}