2

I have a requirement to show real time update of the number of people who did some action. I implemented this functionality by making an ajax request to the server every 20 seconds. But this ajax request happens even if the tab is not in focus/no one is looking at the update. Is there a way to figure out if the tab is active?

I have the following code(simplified version) and it doesn't work.

timer = undefined
$(document).ready ->
  timedCountUpdate()
  window.top.onblur = ->
    clearTimeout(timer)
  window.top.onfocus = ->
    timer = timedCountUpdate()

@timedCountUpdate = () ->
  timer = setTimeout(updateCountIndicator, 20000)

@updateCountIndicator = () ->
  $('.indicator').html = 100
  timedCountUpdate()

I still see the call being made every 20s even if i am not in the tab that has the app loaded. I am testing in chrome.

usha
  • 28,973
  • 5
  • 72
  • 93

3 Answers3

2

In Coffeescript w/ jquery:

$ ->
  timeout_id = null

  resumeTimer = () ->
    # make ajax call here

    # Prevent multiple timers from operating simultaneously:
    clearTimeout timeout_id if timeout_id?

    # Recursive step (ideally fires in 'success' handler of ajax call)
    timeout_id = setTimeout(resumeTimer, 2000)

  $(window.top).focus () =>
    resumeTimer()
  $(window.top).blur () =>
    clearTimeout timeout_id

  # Start timer immediately:
  resumeTimer()
Paul B
  • 198
  • 6
2

I know this is an old question, but I stumbled upon it in a Google search and wanted to provide another alternative that's better suited for what you're wanting to do.

The Page Visibility API is how these types of things should be done moving forward (or now IE10+). The API provides a visibilityChange event that triggers when the visibility of the tab changes. In the callback, checking the document.hidden property will tell you whether the tab is hidden or not.

From there, clear your interval or start it back up again.

Benjamin Solum
  • 2,281
  • 18
  • 29
0

In your case, i would do something like :

var tab_paused = false; // global

if (typeof window.top.onblur === 'function')
{
    window.top.onblur = function() {
     tab_paused = true;
    };
}
if (typeof window.top.onfocus === 'function')
{
    window.top.onfocus = function() {
     tab_paused = false;
    };
}
if (typeof document.onfocusout === 'function')
{
    document.onfocusin = function() {
     tab_paused = true;
    };
}
if (typeof document.onfocusin === 'function')
{
    document.onfocusin = function() {
     tab_paused = false;
    };
}

var ctx = setInterval(function() {
 if (tab_paused === false)
 {
  $('.indicator').html(100);
 }
}, 100);
Paul Rad
  • 4,820
  • 1
  • 22
  • 23