'How does requestAnimationFrame really work?

The official document says The method takes a callback as an argument to be invoked before the repaint. (https://developer.mozilla.org/en-US/docs/Web/API/window/requestAnimationFrame)

I wrote a simple code below:

<html>
    <div style="width: 10px; height: 10px; background: #999"/>
    <script type="text/javascript">
        let count = 0;
        function step() {
            document.getElementsByTagName("div")[0].style.marginLeft = `${count ++}px`
            window.requestAnimationFrame(step)
        }
        step()
    </script>
</html>

My question is how to understand before the repaint? And why it works?

  1. Can we just divide the running process of browser to repainting and before repainting, and requestAnimationFrame just avoid the callback invoked in painting process?

  2. When browser repaint caused by the step, and the step will be invoked before the next repaint, but the repaint actually caused by the step. Is it paradox?



Solution 1:[1]

  1. and 2. - you can looks like fantasy of steps s1,s2...:

s1 browser want to start the repainting of "main repainting" of page - like a background comparatively to the callback function

s2 before this "main" repainting browser perform "calculated part of repaint" call back function on the timeline of future "main repainting"

s3 browser start to work repaint and do in parallel: background="main repainting" and "calculated part of repaint" on the one same timeline.

to perform the step s3 browser must to "calculate before" because code of callback function is custom that code of background of main page

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 JurijsReact