Question presented to candidate: "Say a component polls a server every few seconds using setInterval. How would you use the Page Visibility API to pause that polling when the user switches to a different browser tab, and resume it when they switch back?"
What a strong answer should cover:
- document.visibilityState reports either "visible" or "hidden", and the document fires a "visibilitychange" event whenever that value changes.
- Add a visibilitychange listener on document, check document.visibilityState inside the handler, call clearInterval when it becomes "hidden", and start a fresh setInterval when it becomes "visible" again.
- Store the interval id so it can be cleared safely, and guard start/stop so a second interval never gets created on top of a running one.
- Always remove the event listener and clear any running interval in a cleanup step (component unmount, page teardown) to avoid leaks.
- Real motivation: a backgrounded tab wastes network requests, CPU, and battery if it keeps polling at full speed while nobody is looking at the screen.
Clarifying questions expected:
- "Should the poller fire an extra poll immediately when the tab becomes visible again, or just resume the normal cadence on the next tick?"
- "Is this for a framework component with its own cleanup lifecycle, such as a React useEffect, or plain vanilla JavaScript?"
Code / implementation expected: Yes — a small, runnable utility that starts and stops a setInterval-based poller based on document.visibilityState and the visibilitychange event.