← CodeClarityLab Home
Browse by Category
+ added · updated 7d
← Back to glossary

Page Visibility API

javascript HTML5 Beginner

TL;DR

The Page Visibility API tells you when a tab is hidden or visible — use it to pause animations, polls, and video when the user switches tabs.

Explanation

document.visibilityState is 'visible' or 'hidden'. The visibilitychange event fires when it changes. Use cases: pause autoplay video when tab hides, stop polling when hidden (save bandwidth/battery), pause Canvas animations, pause WebSocket reconnection attempts. document.hidden is a boolean shorthand. The API fires reliably on tab switch, minimise, and screen lock. On mobile, it fires on home button press. Page Visibility should be the primary trigger for any 'pause when not visible' logic.

Common Misconception

The blur event is equivalent to Page Visibility — blur fires when the window loses focus (clicking other app) but the page may still be visible. Page Visibility fires on tab hide.

Why It Matters

Stopping background processing when tabs are hidden reduces CPU/battery usage and data consumption — significant for mobile users.

Common Mistakes

  • Using blur/focus events instead of visibilitychange for tab-switch detection.
  • Not pausing WebSocket reconnection when page is hidden — wastes connections.
  • Not resuming state when page becomes visible again.

Code Examples

✗ Vulnerable
// Always polling regardless of tab visibility:
setInterval(fetchUpdates, 5000);
✓ Fixed
let pollInterval;

function startPolling() {
    pollInterval = setInterval(fetchUpdates, 5000);
}

function stopPolling() {
    clearInterval(pollInterval);
}

document.addEventListener('visibilitychange', () => {
    document.hidden ? stopPolling() : startPolling();
});

startPolling(); // Start initially

Added 23 Mar 2026
Edited 5 Apr 2026
Views 111
Rate this term
No ratings yet
🤖 AI Guestbook educational data only
| |
Last 30 days
0 pings W 0 pings T 0 pings F 0 pings S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T 0 pings F 0 pings S 0 pings S 0 pings M 0 pings T 0 pings W 0 pings T 0 pings F 0 pings S 0 pings S 3 pings M 0 pings T 1 ping W 1 ping T 2 pings F 2 pings S 1 ping S 3 pings M 0 pings T 1 ping W 0 pings T
No pings yet today
Google 28 ChatGPT 25 Perplexity 14 Amazonbot 13 Unknown AI 4 Majestic 2 Ahrefs 1
crawler 84 crawler_json 1 pre-tracking 2
DEV INTEL Tools & Severity
🟢 Low ⚙ Fix effort: Low
⚡ Quick Fix
Pause polls, animations, and video on visibilitychange when document.hidden is true. Resume on visible.
📦 Applies To
javascript HTML5 web
🔗 Prerequisites
🔍 Detection Hints
visibilitychange|document.hidden
Auto-detectable: ✗ No
🤖 AI Agent
Confidence: Low False Positives: Medium ✗ Manual fix Fix: Low Context: File

✓ schema.org compliant