Skip to solution
easyPhone Screen

How would you use the Page Visibility API to pause a setInterval-based poller when a user switches to a different browser tab?

722 views
01

Understand the problem

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.

perf-apitrickyreal-world
02

Attempt it yourself

Sketch your approach before reading the solution — that's what interviews test.

Nudge consolestandby

Stuck? Beam a request up — the console returns a conceptual nudge that guides your logic without spoiling the implementation.

03

Study the solution

Target Audience: Engineers preparing for JavaScript browser-API interview questions. Difficulty: Medium

How to read this doc: Concepts are explained in plain language first, then tagged with 📌 Interview term:. Every result below was actually run against a real jsdom document on Node.js v24.

Solution ready — 2 min read

Classified // press E to declassify

04

Run the code

JSVisibility-aware poller: pauses on hidden, resumes on visible (run directly)
05

Join the discussion

Discussion (0)

Sign in to join the discussion.

No responses yet. Be the first to share what you think.

Transmission complete // awaiting log

KEEP THE
STREAK ALIVE.

Dossier 16 of 165 decoded in the JavaScript track. One more won't hurt.

Back to track