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.


1 Answer 1


As you noticed, you should call requestAnimationFrame only once per frame. It means that you need to call it once upon starting your game, and then once at the end of the same function it calls. For instance:

function draw() {
    if (onCutScene) drawCutScene();
    else if (onMainMenu) drawMainMenu();
    else if (inGame) drawGame();
    else if etc... //Or use a gameState variable and a switch..case

The inner functions should not call requestAnimationFrame again.

  • \$\begingroup\$ When I make these changes, the main menu still continues to run much faster than intended, and the cutscene animations do not happen at all. \$\endgroup\$
    – Wadoo9
    Jul 23, 2016 at 6:02
  • \$\begingroup\$ I figured out why the cutscene animations were not happening and fixed that. But, when I use both requestAnimationFrame calls as you suggested, the game runs at double the speed. When I only use one, it runs at the normal speed. Is this a fault in my coding? \$\endgroup\$
    – Wadoo9
    Jul 23, 2016 at 6:41
  • 1
    \$\begingroup\$ Probably, because in my code it is being called only once at a time. Remember that you need to remove the call from inside your specific functions too. Search your entire source for any remaining calls and remove them. Also, make sure the first call is not inside any loop or timer, it should be called only once when your game starts. \$\endgroup\$
    – rcpinto
    Jul 23, 2016 at 7:56
  • \$\begingroup\$ I figured out what was happening. In my HTML code, I am calling the init() function onload. Once I removed that call, everything is working as you described. \$\endgroup\$
    – Wadoo9
    Jul 23, 2016 at 16:15

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .