DEV Community

Discussion on: Animating Sprite Sheets With JavaScript

Collapse
 
martyhimmel profile image
Martin Himmel

requestAnimationFrame returns a long integer. If you assign that to a variable, you can then call cancelAnimationFrame(id) once the required condition is met to stop the cycle.

Using the step function as an example, something like this:

let animationFrameId;

function step() {
    if (animationFrameId && conditionToStopCycle) {
        window.cancelAnimationFrame(animationFrameId);
        return;
    }
    // rest of the code
    animationFrameId = window.requestAnimationFrame(step);
}
Enter fullscreen mode Exit fullscreen mode

Another way could be to return early to break out of the step function. If only one cycle is needed, once the counter reaches the end of the array, return before calling the next requestAnimationFrame (instead of reseting the counter to 0 and continuing).

Here are the MDN pages for requestAnimationFrame and cancelAnimationFrame.

Collapse
 
deedeessay profile image
deedee resists!

Thank you... I really appreciate your help.