About this article
This article was created using an automated generation workflow leveraging generative AI. It retrieves the Page Visibility section of the HTML Standard and the MDN Page Visibility API documentation, explaining concepts by cross-referencing the execution button and counter implementations of existing demos.Verification Status: 📘 Official information confirmed – Code statically inspected – Browser operation of the live demo not verified
When you switch tabs and return, the on-screen counter has advanced by the number of seconds you waited. If what you want to measure is the 'total duration the page was displayed,' it is problematic to include the time spent in the background. By using the Page Visibility API, you can determine whether the page is visible or hidden and accumulate only the visible intervals.
Live demo to try the counter that advances only while visible
- What you will learn in this article
- Try the demo first
- What is called 'visible'?
- The core of implementation is "adding intervals"
- Compare under different conditions
- focusand the difference from clicks
- When observation does not work well
- Considerations for practical application
- Sources and Implementation
- GitHub Sample
What you will learn in this article
In this tutorial, you press 'Run' to start measuring, switch to another tab, and return a few seconds later. The time spent in the background is not added to the counter. In the comparison, you will shorten or lengthen the background time and repeat switching between visible and hidden states several times.
The Page Visibility API only indicates whether the document is visible within the browser. It cannot determine whether 'the user was looking at the screen' or 'was working.' Let's first understand that it cannot be used as proof of work hours or for finalizing billable hours.
Try the demo first
Press 'Run'. The result section displays 'Please switch to another tab and return,' and the elapsed seconds update.
Memorize the displayed seconds, switch to another tab, wait 5 to 10 seconds, and return.
Observe the value immediately after returning. The observation point is that the elapsed seconds while waiting are not instantly added to the value from before it was hidden.
Pressing 'Run' again allows you to restart the measurement.
This demo does not use text input. The target of measurement is the display state of the demo page itself. It is normal even if there are no input fields. The operational conditions are the 'duration of waiting in the background' and 'the number of times switching between visible and hidden states.'
What is called 'visible'?
In the HTML Standard, the visibility state of a document is visible or hidden. When the browser detects that a tab has been switched, a window minimized, or the screen turned off, it updates the document state and fires the visibilitychange event. The event itself does not carry the duration for which the page was viewed. The event handler reads the current state and selects the necessary processing.
According to the MDN documentation, document.visibilityState returns the state as a string, and document.hidden returns a boolean indicating whether the element is hidden. This tutorial uses the latter. Both are APIs for reading state and are not APIs for instructing the browser to stop timers.
In the diagram, active viewing intervals are bounded by start and end events, and only their durations are summed. No new intervals are started while the page is hidden.
flowchart LR
A["表示中:計測開始"] --> B["hidden:区間を加算"]
B --> C["visible:次の区間を開始"]
C --> D["表示中の時間だけ合計"]
The flow is: "finalize the total when hidden, and start the next measurement interval when returned to visible." The key point is to use the difference between the state-change time and the current time, rather than counting how many times the update timer is called while hidden.
The core of implementation is "adding intervals"
The processing in the demo's "implementation code," simplified for explanation, is as follows.
let visibleMs = 0;
let visibleFrom = document.hidden ? null : performance.now();
function onVisibilityChange() {
if (document.hidden && visibleFrom !== null) {
visibleMs += performance.now() - visibleFrom;
visibleFrom = null;
} else if (!document.hidden && visibleFrom === null) {
visibleFrom = performance.now();
}
}
document.addEventListener("visibilitychange", onVisibilityChange);
const refresh = setInterval(() => {
const currentVisibleMs =
visibleMs +
(visibleFrom === null ? 0 : performance.now() - visibleFrom);
showSeconds(currentVisibleMs / 1000);
}, 100);
visibleMs is the total of completed viewing intervals.visibleFrom is the start time of the currently ongoing viewing interval, or null if hidden. The time difference is added to the total only when the page becomes hidden, and the start time is reacquired when the page is redisplayed. The displayed value is calculated as "confirmed total + ongoing interval".
performance.now() is a monotonically increasing clock used to measure elapsed time within this page. It is suitable for avoiding issues where measurements roll back due to changes in wall-clock date and time. However, this time difference should not be interpreted as a measure of actual work time or human attention. Value precision may be degraded by browsers for privacy protection, and this is not an example intended for strict sub-millisecond measurement.
In the code example, setInterval is used to update the display. Even in hidden tabs, the timer itself remains registered, and browsers may throttle processing frequency for background tabs. The primary reason the counter does not count background time is not because the browser stops setInterval, but because the design closes the viewing interval when hidden and does not open the next interval until return. Stopping periodic updates when unnecessary further reduces processing overhead.
In the actual demo, the common runner's "Run" button starts this measurement function, and cleans up previous timers and event listeners before starting the same process again. The article excerpt is structured to explain the mechanism, and screen display function names conform to the tutorial's common code.
Compare under different conditions
| Experiment | Operation | Expected observation |
|---|---|---|
| Shorten the background time | Display for a few seconds, then switch to another tab, wait for about 3 seconds, and return | Several seconds worth of time from before entering the background are not added all at once |
| Lengthen the background time | Wait for about 15 seconds using the same procedure | Just like the 3-second experiment, the 15 seconds in the background are not included in the total active display time |
| Perform switching multiple times | Repeat display -> background -> display 2 to 3 times | Each displayed interval accumulates |
| Restart measurement midway | Click "Run" again | Does not carry over previous measurement results and starts a new measurement |
Although the screen updates every 100 milliseconds, the displayed value is recalculated from the elapsed time, so strict 0.1-second accuracy is not guaranteed. The slight variation in values immediately after returning is due to the timing of screen rendering and event processing. What you should look at is whether "the entire duration it was hidden was added."
focusand the difference from clicks
Loss of window focus and document invisibility are not identical conditions. For example, even if another window overlaps, the browser tab itself may still be determined as visible. A state where part of the screen is visible may also fall under the specification'svisible. Conversely, on mobile devices, switching to another app or turning off the screen can triggerhidden.
Therefore, this is useful for purposes such as pausing animations displayed on the screen, pausing videos, or creating a simple counter for visible duration only. It is insufficient for measuring actual reading time by users, work attendance, billing, or identity verification for security. If necessary, design a separate mechanism tailored to your purpose, such as explicit start/stop operations or server-side auditable records.
When observation does not work well
Values do not increase: First, check if you clicked "Run". Measurement does not start just by displaying the page initially.
Numbers advance slightly after returning: This is a normal update because a new interval is measured from the point when the display state returns.
Numbers on the screen do not change even when moved to the background: Background tabs may restrict screen rendering and timer updates. Verify whether the numbers update on the active tab.
I want the elapsed time including the time spent in the background: This tutorial measures something different. Use a clock that measures elapsed time regardless of the tab state, and use the Page Visibility API to determine when to throttle rendering processes.
It starts from zero after reloading: There is no feature to save measurement results. If you need to record data even after reloading, design the storage scope, retention period, and personal data handling separately.
Considerations for practical application
For in-page animations, you can stop animation frame requests and audio playback when the state changes to hidden, and restore the state when it returns to visible. Do not assume that long-running communication or data persistence will always complete successfully simply because the state is hidden; design critical save operations to handle failures well before state changes occur. MDN describes the transition to hidden as the last reliable signal observable from outside the page, but this does not eliminate the possibility that the page may be terminated before the event is dispatched.
The API does not record user attention or work content. This sample does not require any input and only displays numeric values within the demo. Because the shared demo page uses an external library to render diagrams, diagrams may not appear depending on the network environment. Since the source code for the diagrams is also included in the article, you can follow the workflow even if the diagrams fail to render.
Sources and Implementation
Scope of live demo review: We reviewed the learning material's HTML and common JavaScript together on GitHub. The live demo URL returned a 403 error in the viewing tool, so we could not verify page reachability, button operations, or browser behavior from this execution environment. Please perform the aforementioned operations in a browser that can open the page.
