RequestAnimationFrame detect stop

I noticed that whenever I dock a browser window or switch tabs requestAnimationFrame stops being called (which I expect to happen).

Is there any way to detect when this stop occurs?

The reason is that there is a timer in my game. I want to stop the timer when requestAnimationFrame is no longer rendering.

I looked at the window.blur and window.focus events, but they are not related to when requestAnimationFrame stops and fires (for example, when you click outside the browser window, the window.blur event fires, but requestAnimationFrame continues to work).

I want to subscribe when requestAnimationFrame starts and stops. Do you know a way?

+4
source share
2 answers

If you know that under normal circumstances the requestAnimationFrame triggered by, say, at least 4 Hz, you can set the timer to, say, 3 Hz, and if there was no requestAnimationFrame between the timer marks, the requestAnimationFrame timer requestAnimationFrame stopped.

+1
source

try the following:

 var timer; if (!window.requestAnimationFrame) { window.requestAnimationFrame = window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame; } requestAnimationFrame(function again() { if (timer === "paused") { return; } clearTimeout(timer); timer = setTimeout(function () { timer = "paused"; console.log("got ya, you closed the window"); requestAnimationFrame(function () { timer = null; console.log("got ya, you re-opened the window"); requestAnimationFrame(again); }); }, 1e3); // rest of code goes here requestAnimationFrame(again); }); 

Need more info? just ask.

+1
source

Source: https://habr.com/ru/post/1442913/


All Articles