1
\$\begingroup\$

Over on SO I posted a question: Change transition duration during loop with requestAnimationFrame which hasn't got any responses just yet. I've since come up with this idea and wanted to know if there was any way to improve it.

Essentially I would like to loop over an array of elements that have a smooth transition (a different state to normal) when swapping between them.

Instead of setting a setTimeout during Array.forEach, then using requestAnimationFrame to loop over the whole thing. I'm now using requestAnimationFrame for the main loop and Array.shifting to work on the current element.

Any ideas for improvement? Is this efficient?

function animateArray(fooArray, bar) {

    // Timing
    var start = null;
    var interval = 3000; // how long each element in the array will be displayed for
    var intro = 1000; // easing/tweening in duration
    var outro = 1000; // easing/tweening out duration
    var last = 0 // The last interval, 
    var current; //current element of array
    var fooLength = fooArray.length;

    function update(timestamp) {

        // get the start time and progress
        if (!start) start = timestamp;
        var progress = timestamp - start;

        // do something every `interval` seconds (if it can)
        if(!last || timestamp - last >= interval) {
            last = timestamp;

            // pull off the first element in the array to work on
            current = fooArray.shift();
        }

        if (typeof current !== null) {

            // Do something during the intro
            if (timestamp < last + intro) {
                console.log(`${current}-intro`);

            // The main animation
            } else if (timestamp > last + intro && timestamp < last + (interval - outro)) {
                console.log(`${current}`);

            // do something else during the outro
            } else {
                console.log(`${current}-outro`);
            }
        }

        // loop
        if (progress < interval * fooLength) {
            requestAnimationFrame((timestamp) => update(timestamp, fooArray, bar));
        }

    };

    requestAnimationFrame((timestamp) => update(timestamp, fooArray, bar));
}

animateArray([1,2,3], 'bar');  
\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.