Skip to content
  • Home
  • About
  • No Access
  • Privacy Policy
Bits of .NET
Bits of .NET
  • C#
  • Asp.Net Core
  • SQL
  • Windows
  • WordPress
  • AI
  • JavaScript
  • CSS
  • MORE
    • HTML
    • Ajax
    • Git
    • Docker
    • Kubernetes
    • Photoshop
    • Visual Studio

Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

  • C#
  • Asp.Net Core
  • SQL
  • Windows
  • WordPress
  • AI
  • JavaScript
  • CSS
  • MORE
    • HTML
    • Ajax
    • Git
    • Docker
    • Kubernetes
    • Photoshop
    • Visual Studio
Ajax

Ajax: Fix a Polling Loop Doubling After a Tab Regains Focus

- 28.11.26 - ErcanOPAK

🔄 Fix a Polling Loop Doubling After a Tab Regains Focus

Adding a visibilitychange listener that polls immediately when a backgrounded tab becomes visible again is a reasonable way to make a view feel fresh after a user comes back to it – but if that immediate poll doesn’t also reset the page’s existing setInterval, the original timer keeps running on its own untouched schedule. The tab regains focus, the immediate poll fires right away, and the regular interval’s own next tick – already due from before the tab was backgrounded – lands only a few seconds later, so two fetches end up overlapping, and if the poll function has no in-flight guard, both run to completion and both apply their own, possibly differently-timed, results to the UI.

🔎 The Problem

let pollTimer = setInterval(fetchUpdates, 15000);

document.addEventListener('visibilitychange', () => {
  if (document.visibilityState === 'visible') {
    fetchUpdates(); // poll immediately so the view feels fresh again
    // BUG: the original setInterval(fetchUpdates, 15000) from page load
    // is still running on its OWN 15-second clock, untouched - it does
    // not know an extra poll just happened
  }
});

// Tab backgrounded for 40s, regains focus at second 0:
//   -> immediate poll fires right away (visibilitychange handler)
//   -> the original interval's next tick was already due around
//      second 5-10 depending on when it last fired before backgrounding
//   -> two fetchUpdates() calls land within a few seconds of each other,
//      and if fetchUpdates() has no in-flight guard, both run fully and
//      both apply their (possibly differently-timed) results to the UI

✅ Fix: Reset the Interval on Focus

  • Clear and restart the interval inside the visibilitychange handler (clearInterval the old timer, call fetchUpdates(), then start a fresh setInterval) so the immediate poll also resets the regular schedule’s clock instead of running alongside it.
  • Add a simple in-flight guard inside fetchUpdates() itself so a poll triggered while a previous one is still in flight skips instead of stacking a second concurrent request.
  • If the endpoint behind the poll has any non-idempotent side effect (marking something as read, incrementing a view counter, firing an analytics event), make that specific action idempotent server-side rather than relying on the client to never possibly call it twice – a fixed client bug today doesn’t protect against the next one.

🚨 Why This Is Dangerous

Two overlapping polls landing a few seconds apart from each other rarely crashes anything, which is exactly why it’s easy to ship – the visible symptom is usually just a duplicated notification or a double-counted event, and neither looks like a timer bug until someone actually goes looking for one.

A visibilitychange handler that fires an extra poll is only an optimization if it also knows about the regular poll it’s running alongside – otherwise it’s just a second, unsynchronized timer.

— Frontend Engineer

Related posts:

Ajax: Fix CORS Errors When Calling APIs from Different Domains

Ajax: Fix CORS Errors When Calling APIs from Different Domains

Ajax: REST vs GraphQL — Choosing the Right API

Ajax: REST vs GraphQL — Choosing the Right API

Ajax: Fix navigator.sendBeacon Silently Dropping a Payload Over 64KB With No Error Reported on Page ...

Ajax: Fix navigator.sendBeacon Silently Dropping a Payload Over 64KB With No Error Reported on Page ...

Views: 7
Found this useful? Share it
XLinkedInWhatsApp

Post navigation

Visual Studio: Fix Code Cleanup on Save Skipping a Format Rule
CSS: Fix a :has() Selector Never Matching an SVG Child

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

Most Read

  1. 01How to make theater mode the default for Youtube 1,079 views
  2. 02How to add default value for Entity Framework migrations for DateTime and Bool 997 views
  3. 03Get the User Name and Domain Name from an Email Address in SQL 996 views
  4. 04Get the First and Last Word from a String or Sentence in SQL 873 views
  5. 05How to select distinct rows in a datatable in C# 868 views
  6. 06How to enable, disable and check if Service Broker is enabled on a database in SQL Server 671 views
  7. 07Add Constraint to SQL Table to ensure email contains @ 631 views
  8. 08Average of all values in a column that are not zero in SQL 584 views
  9. 09How to use Map Mode for Vertical Scroll Mode in Visual Studio 562 views
Bits of .NET

Daily micro-tips for C#, SQL, performance, and scalable backend engineering.

Social

  • ErcanOPAK.com
  • GoodReads
  • LetterBoxD
  • Linkedin
  • The Blog
  • Twitter
Back to top
© 2026 Bits of .NET | Built with Xblog Plus free WordPress theme by wpthemespace.com