requestAnimationFrame - Tell when browser loses focus

2.5k views Asked by At

From what I have read requestAnimationFrame can tell when the browser loses focus. Is there some kind of event that fires when this occurs? I'm looking to pause and resume code in connection with requestAnimationFrame.

1

There are 1 answers

0
AudioBubble On

requestAnimationFrame is not an element on which an event can be or is fired when the browser loses focus; it just sets up a callback. But standard behavior is that when the browser/tab goes out of focus, callbacks are paused. Therefore, most likely your code (if in a callback) is already being paused.

There is a possibility that all browsers may not pause callbacks, but instead slow them down. However, the W3C spec would seem to imply pausing, not slowing:

Whenever a Document's hidden attribute ([Page Visibility]) is false and the animation frame request callback list is not empty, the user agent MUST regularly queue a task...

If d's hidden attribute is true, continue to the next entry in the contexts list.

If you want to be absolutely sure your code is pausing when the tab is out-of-focus, or if the code you are trying to pause is not structured as part of a RAF callback, then you could consider using the Page Visibility API.

Note that both RAF and Page Visibility API are available only in IE>=10.