Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

requestAnimationFrame detect stop

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

Is there a way to detect when this stop occurs?

Reason is, that I have a timer running in my game. I want to stop the timer when requestAnimationFrame is no longer rendering.

I've looked into the 'window.blur' and 'window.focus' events, but these are not related to when requestAnimationFrame stops and starts (eg when the you click outside the browser window a window.blur event is fired but requestAnimationFrame keeps running).

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

like image 850
ChrisRich Avatar asked Oct 30 '12 05:10

ChrisRich


People also ask

How do I stop requestAnimationFrame?

If you assign your requestAnimationFrame() method to a variable, you can use the cancelAnimationFrame() method to cancel it before it runs.

What is the aim of the requestAnimationFrame method?

requestAnimationFrame() method tells the browser that you wish to perform an animation and requests that the browser calls a specified function to update an animation before the next repaint. The method takes a callback as an argument to be invoked before the repaint.

Is requestAnimationFrame better than setInterval?

requestAnimationFrame() is much more efficient than setTimeout() or setInterval() , and the result is smoother and more accurate (just check the provided demo and the consumed CPU).

Is requestAnimationFrame necessary?

To optimize system and browser resources, it is recommended to use requestAnimationFrame , which requests the browser to execute the code during the next repaint cycle. This allows the system to optimize resources and frame-rate to reduce unnecessary reflow/repaint calls.


2 Answers

If you know that under normal circumstances requestAnimationFrame fires at, say, at least 4 Hz, you can set a timer for, say, 3 Hz, and if there has been no requestAnimationFrame tick between the timer ticks, the requestAnimationFrame timer has stopped.

like image 100
icktoofay Avatar answered Sep 20 '22 14:09

icktoofay


try this:

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.

like image 45
Roderick Obrist Avatar answered Sep 23 '22 14:09

Roderick Obrist