Do calls to requestAnimationFrame stack?

Viewed 73

I have the following functions

function render() {
  init = timeStep(init)
  if (steps <= yQuotient) {
    requestAnimationFrame(render)
  }
}

export function fire() {
  setup();
  render();
}

I then call fire() whenever I need to start/restart the application. My question is whether this will result in multiple requestAnimationLoop()'s active simulatenously as they build up like eventListeners do when called repeatedly, presumably affecting performance.

Do I need to amend my fire() function to something like this?

export function fire() {
  cancelAnimationFrame(render)
  setup();
  render();
}

Or does requestAnimationLoop() just automatically know to end it's current loop when a new one is started?

1 Answers

Yes, calls to requestAnimationFrame will stack all the callbacks into the map of animation frame callbacks.

Each painting frame, the keys of this map are all gotten and looped over, allowing to schedule a new animation frame callback from such a callback, for firing at the next painting frame.

So yes, scheduling multiple times the same callback in the same event loop iteration will worsen the performances of your page, since it will have to do multiple times the same work.

It's quite unclear how all your system works, but a quite often used strategyfor games and interactive animations is to keep a single main animation loop running all the time and calling sub-tasks. External events only modifying states of objects that get visited from these sub-tasks.

Related