最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - requestAnimationFrame detect stop - Stack Overflow

programmeradmin1浏览0评论

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?

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?

Share Improve this question asked Oct 30, 2012 at 5:54 ChrisRichChrisRich 8,75611 gold badges51 silver badges73 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

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.

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.

发布评论

评论列表(0)

  1. 暂无评论