I have JavaScript that is doing activity periodically. When the user is not looking at the site (i.e., the window or tab does not have focus), it’d be nice to not run.
Is there a way to do this using JavaScript?
My reference point: Gmail Chat plays a sound if the window you’re using isn’t active.
Since originally writing this answer, a new specification has reached recommendation status thanks to the W3C. The Page Visibility API (on MDN) now allows us to more accurately detect when a page is hidden to the user.
Current browser support:
The following code falls back to the less reliable blur/focus method in incompatible browsers:
onfocusinandonfocusoutare required for IE 9 and lower, while all others make use ofonfocusandonblur, except for iOS, which usesonpageshowandonpagehide.