I am having issues with requestAnimationFrame calls stacking on top of each other. I am developing a platformer game, which has three separate functions that need animating (main menu, cutscene, in game). Currently, I have flags to determine when to run requestAnimationFrame. For example, I only call requestAnimationFrame in the runCutscene() method if !onMainMenu and !inGame. These flags are reset in the init() method, which decides which of the three methods to run.
Specifically, my problem occurs when I return to the main menu from the cutscene (at seemingly random times, I can not continuously replicate the error). The main menu appears to run at double its normal speed (which I assume is because of stacked requestAnimationFrame calls).
What is the most efficient way to call requestAnimationFrame? If I put the requestAnimationFrame call in the init() method, the game breaks. Thank you in advance.