Skip to the solution
EasyPhone Screen7 min read

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

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-api
  • tricky
  • real-world

Try it yourself

Sketch your approach before you read the solution. That is what the interview tests.

Stuck? Get a hint.

A short nudge toward the approach. It will not give the answer away.

Solution

The solution is hidden so you can try first

7 min read Β· 8 sections

Run the code

Edit the code and run it here. Each console line with an expected value becomes a test.

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

Discussion

Other approaches, follow-ups and how it went in real interviews.

Sign in to join the discussion.

No comments yet. Share how you would answer it.

Question 16 of 165 in JavaScript

Keep your momentum going.

Mark this question solved to track your progress, then take the next one while it is fresh.

Up nextEasy

What is the difference between preventDefault and stopPropagation?

Continue