I basically have a lerp function similar to this one: Client interpolation for 100% serverside game when a new server update is received, the update frequency is added to a variable (msAhead) and the delta is subtracted from it every client frame. But when I do it the variable msAhead increases a lot when the tab is switches from inactive to active. Here is my code:

msAhead += updateFrequency; //when new update is received. 

(function loop(now) {

var now = Date.now();
delta = now - Time;

Time = now;

msAhead -= delta;   




How can I fix my issue?


requestAnimationFrame only gets called when the canvas is getting rendered by the web browser's rendering engine. When the canvas is not on the screen, no animation frames will get requested.

If you need to do processing while the tab is inactive, you can:

  • use setInterval, but keep in mind that it gets throttled to once per second when the tab is inactive
  • use a WebWorker
  • \$\begingroup\$ In theory, even though the loop is frozen, the delta values would still increase to compensate the frozen loop? I would rather have the loop frozen than to be constantly computing something in the background. \$\endgroup\$
    – Dup Dup
    Dec 15 '18 at 1:44
  • \$\begingroup\$ @DupDup some game systems will implement this by enforcing a maximum timestep. If the time since the last frame and this one exceeds some threshold, we pretend it was actually only as long as the threshold, and discard the rest of the time. This has the effect of making the game run slower than realtime when these big jumps happen, but it's often preferable to bogging down the experience while the simulation catches up. \$\endgroup\$
    – DMGregory
    Jan 14 '19 at 3:37

Aside from DMGregory suggestion to enforce a maximun timestep...

You can use the visibility API. To do so, you will register an event handler visibilitychange event of the document. It will fire when the user switches tab from or to your page. In the event handler you can use Document.hidden or Document.visibilityState to check if it is visible.

It is up to you how you will handle that time... If what you want is for it not contribute to the delta, what you have to do is measure it, and substract it from the delta on the next loop.

By the way, the user can mess with Date.now() by changing system time. You might want to use performance.now().


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.