javascriptrequestanimationframe

Understanding how requestanimationFrame works


I am trying to understand the requestAnimationFrame api but I am not able to understand how repaint occurs during the process.

I am working on a programming exercise to create a stopwatch.

function startTimer() {
  timerId = requestAnimationFrame(updateTimer);
}

function updateTimer() {
   timer.textContent = updateTime();
   timerId = requestAnimationFrame(updateTimer);
}

I understand that the requestAnimationFrame tells the browser to call the callback function updateTimer before the next browser repaint. But, I am assuming that the calculations inside the callback function updateTimer are causing the repaint in the first place.

So, I am struggling to understand how the repaint is triggered in this scenario? Does requestAnimationFrame triggers the repaint?


Solution

  • Does requestAnimationFrame triggers the repaint?

    Not really no. It will force the browser to queue an update the rendering task, and, in Chrome, it will cause a Composite Layer, meaning it's not free, but it's not necessarily equivalent to a full "paint".

    What will cause a new paint in your case is that you changed the textContent of your node, and, unless the node isn't in the tree, or hidden, this will force a paint after the next update the rendering.

    You can think of requestAnimationFrame as a setTimeout(fn, time_before_next_paint). It only schedules your callback, and then forces a lot of minor checks, but these would anyway have happened even if using another timer method.