简体   繁体   中英

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?

如果您知道在正常情况下requestAnimationFrame会以(例如,至少4 Hz)触发,您可以设置一个定时器,例如3 Hz,如果在定时器滴答之间没有requestAnimationFrame滴答,则requestAnimationFrame定时器已停止。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM