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.
Learn more (2019 update)
- All modern browsers are supporting
document.hidden
- http://davidwalsh.name/page-visibility
- https://developers.google.com/chrome/whitepapers/pagevisibility
- Example pausing a video when window/tab is hidden
https://web.archive.org/web/20170609212707/http://www.samdutton.com/pageVisibility/