I realized that I was confused with requestAnimationFrame
, although some time ago I thought I understood how it works.
So what is the essence of my problem:
They say that requestAnimationFrame
, namely its callback, will be called before the rendering stages, that is, calling requestAnimationFrame
does not mean that the browser will run to execute the callback function passed to it right now.
However, if we take this code:
const run = () => {
requestAnimationFrame((timeStamp) => {
console.log(timestamp);
requestAnimationFrame(run);
})
};
run();
and if we run on a completely empty page, we will see how the timestamps will be printed in the console, but why if the page is completely empty, there is no reason to render. The reason?
Okay, let’s look at the specification, it says you need to wait for rendering opportunity before starting the task related to rendering, where our requestAnimationFrame
will appear. But the code above should not be printed due to the lack of a rendering opportunity reason. Or is the reason exist?
An explanation is needed.
2
Answers
If you are rendering a completely empty page, you are still rendering. The fact that you can run any javascript code, even call the "run" function means that the page has rendered.
A rendering opportunity in my opinion should be automatic. How will you get a video to work when unless browser renders the update at highest possible frequency (according to its refresh rate).
Although it is not detailed upon, I think the below holds significance:
This is what I speak of Rendering opportunities typically occur at regular intervals.. Typically is used because there are instances when browser is not free to render in the upcoming interval, and that is when we lose frames.
So I think it is the browser’s job to generate rendering opportunities, and the event loop spec mentions that for every rendering opportunity animation frame callbacks are supposed to be run: