Endless animations, requestAnimationFrame and call stack limits

RAF will launch the function "on the next drawn frame". That's means that it will be executed in another stack of action, and you won't have any maximum call stack error.


Yes, requestAnimationFrame() is asynchronously recursive, and that prevents any actual stack overflow. But don't forget that the stack still unwinds at the end. There is no issue if you're running a single animation. But if you are running a series of animations in sequence, you might do something like this:

function animateFirst(timeStamp) {
    let r = functionReturnValue();
    if (r == "complete") {
        frame = requestAnimationFrame(animateNext);
        return; // this is necessary
    }
    frame = requestAnimationFrame(animateFirst);
}

Or you must structure it this way:

function animateFirst(timeStamp) {
    let r = functionReturnValue();
    if (r == "complete") {
        frame = requestAnimationFrame(animateNext);
    }
    else {
        frame = requestAnimationFrame(animateFirst);
    }
}

These examples are oversimplifications. In an actual animation function there might be more complex logic. The point is that if you leave out the return statement in the first example, animateFirst() will run again after animateNext() has completed and unwound its async stack. Depending on your code, it might run once, or it might start a whole new animation loop.