For context, I’ve started using Codeium in Visual Studio. I sometimes try to talk about generative AI’s ability to write code, and I thought it would help to get more examples than just ChatGPT. Anyway, it had an observation that I lack the experience to evaluate, so I thought I’d throw it out for more experienced Babylon.js developers.
Following an example somewhere, I had code that looked something like (function and variable names changed due to proprietary code):
engine.runRenderLoop(() => {
do_stuff();
scene.render();
});
Note that a side effect of running do_stuff is that some rendering may change. For example, it displays the current time. It is not necessary for the rendering to occur when that happens. It would be enough to trigger it when the browser gets focus again.
Codeium suggested that instead of using runRenderLoop, I should use requestAnimationFrame. Its argument was that requestAnimationFrame saves resources by not running when the browser is not focused (so no one can see any animation that might be done). I noted that some of what is in do_stuff should be run even if there is no render event and asked if I could get both behaviors. While researching that, I found WebGPU + custom render loop not working
Anyway, the resulting code, which seems to be working:
engine.runRenderLoop(do_stuff);
const render_loop = () => {
engine.beginFrame();
scene.render();
engine.endFrame();
requestAnimationFrame(render_loop);
};
requestAnimationFrame(render_loop);
The idea being that this runs do_stuff at a predictable interval (e.g. sixty times a second) and render_loop as needed.
Is requestAnimationFrame the recommended way to trigger render?
Is it sensible to do things in runRenderLoop that should happen even if rendering does not occur? Or is this a bad way to use runRenderLoop? If it’s bad, is there a recommended alternative way to get that functionality.