In addition to Richard Sim?es answer you can also use the Page Visibility API.
if (!document.hidden) { // do what you need }
This specification defines a means for site developers to programmatically determine the current visibility state of the page in order to develop power and CPU efficient web applications.
document.hidden
1.4m articles
1.4m replys
5 comments
57.0k users