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
2.1m questions
2.1m answers
60 comments
57.0k users