Search code examples
javascriptadditionrequestanimationframeon-the-fly

JavaScript Adding to requestAnimationFrame function


The question could be referred to Three.JS framework, but I think it's a general JS problem.

animate();

function animate() {

    {doSomething}
    requestAnimationFrame( animate );

}

So the function animate() runs every frame and does something.

The question is how to add {doAnotherSomething} to animate() on the fly?

function anEventHappened(){

     //adding some methods to animate

}

Solution

  • There are several ways to do this. But you'll somehow have to foresee something in this animate function that can detect that more needs to be done. This "something" could be an array with functions to execute as extras. Initially that array would be empty, but upon some event you could add a function to that list (or remove one from it).

    Here is a practical example:

    let container = document.querySelector("pre");
    let todoList = []; // <--- list of functions to execute also as extras
    animate();
    
    function animate() {
        todoList.forEach(f => f()); // execute whatever is in the todo-list
        moveText(container);
        requestAnimationFrame(animate);
    }
    
    document.querySelector("button").onclick = function anEventHappened() {
        let newContainer = document.createElement("pre");
        newContainer.textContent = Math.random();
        document.body.appendChild(newContainer);
        todoList.push(() => moveText(newContainer)); // add something extra
    }
    
    // Helper function to perform some HTML-text manipulation
    function moveText(what) {
        what.textContent = what.textContent.includes("<") ? what.textContent.slice(1)
            : what.textContent.length < 60 ? " " + what.textContent
            : what.textContent.replace(/ (\S)/, "<$1");
    }
    <button>Do extra</button>
    <pre>phrase</pre>