engine.getDeltaTime huge when window returns focus

I am using engine.getDeltaTime ensure my simulation performs at a constant rate, but have found that if the tab loses focus, when the user refocuses a potentially huge getDeltaTime is returned.

My solution is below, just wondered if there was a better way.
let hasFocus = true;
let firstOnFocus=false;

engine.runRenderLoop(function () 

    if (hasFocus){
      if (firstOnFocus){
        mainLoop.updateTime(0); // trash the DeltaTime if just returned focus
        firstOnFocus=false;
      } else {
        mainLoop.updateTime(engine.getDeltaTime());
      }
      scene.render();
    }  
});

document.addEventListener(“visibilitychange”, function() {
if (document.visibilityState === ‘visible’) {
hasFocus=true;
firstOnFocus=true;
} else {
hasFocus=false;
firstOnFocus=false;
}
});

Hello and welcome!

The usage of Page Visibility API to avoid large time delta values is quite common and correct.
Here is the example from Yuka library - yuka/src/core/Time.js at master · Mugen87/yuka · GitHub
One may check Yuka+Babylon examples here - Yuka | Examples with Babylon.js

This raises an interesting question to know if time should continue when rendering is paused which honestly probably depends on the use case.

cc @Deltakosh ?

We do have an option for it :slight_smile:

you can set engine.renderEvenInBackground = false

2 Likes