2

I have a web management page I build for my users, this page contain ajax that being call every 4 seconds to display real time information, my problem is that some of my users open this page multiple times on different tabs without noticing it, This cause excessive amount of requests to my php service, is there a way I can set it so once the page is reopened it will stop the old pages from sending requests?

Thanks, Rami.

Toto
  • 77
  • 1
  • 9
  • you can test the session, if you have a session 2 time in a lapstime inferior to 4 sec, just lock this page with a special return and some treatment in javascript ;) – ekans Aug 06 '14 at 12:06
  • I dont know your app, but maybe there is a possibility not to execute those request when window is not active? If there is no need to refresh content when no one is looking at it try this solution : http://stackoverflow.com/questions/15871942/how-do-browsers-pause-change-javascript-when-tab-or-window-is-not-active – WebHQ Aug 06 '14 at 12:11

2 Answers2

1

In modern browser, from IE10 and up, you can use the Visibility API to figure out if the tab is active or not, and only keep polling in an active tab, something like this

var hidden, visibilityChange, timer;

if (typeof document.hidden !== "undefined") {
    hidden = "hidden";
    visibilityChange = "visibilitychange";
} else if (typeof document.mozHidden !== "undefined") {
    hidden = "mozHidden";
    visibilityChange = "mozvisibilitychange";
} else if (typeof document.msHidden !== "undefined") {
    hidden = "msHidden";
    visibilityChange = "msvisibilitychange";
} else if (typeof document.webkitHidden !== "undefined") {
    hidden = "webkitHidden";
    visibilityChange = "webkitvisibilitychange";
}

function handleVisibilityChange() {
    if (document[hidden]) {
        stopAjax();
    } else {
        startAjax();
    }
}

document.addEventListener(visibilityChange, handleVisibilityChange, false);

function startAjax() {
    timer = setInterval(function() {
        $.ajax(options);
    }, 4000);
}

function stopAjax() {
    clearInterval(timer);
}
adeneo
  • 312,895
  • 29
  • 395
  • 388
0

You can write cookie to users machine and on the server check last time when you got request from user. If it was earlier then 4 sec then you do not process this request.

Vova Bilyachat
  • 18,765
  • 4
  • 55
  • 80