I have a Notification System working with AJAX requests over a file called notification-refresh.php
which return a JSON object with new notifications - if it exists.
So each user call this file to push notifications to the browser. Everything was fine until each user starts to open a lot of tabs. Each tab request that file in a 3 seconds interval.
The number of requests overloaded the server and we've temporarily disabled functionality to save our system.
So, can you guys help me? I don't know if that's possible and I looked for other ways to do notification systems with javascript and PHP only, unsuccessfully.
Is there a way to prevent users from running the same javascript call in multiple tabs? Maybe stop the refresh in hidden tabs...
PS: that's not a server side problem. Even when we disabled the notification function, the number of tiny requests just overloaded.
EDIT: final code
All you guys helped me a lot and I found a fast solution to solve my problem. I'll left the code here as it can help people in the future (or not).
Litle things before start:
- there's a global variable named
canRefresh
, responsible to allow or deny access torefresh()
function; - you don't need to do an extra function as I did because you can get the tab focus state with a single call:
document.hasFocus()
, but it's recommended if you pretend to use it on distinct parts of your code; I can't show you the entire code, sorry.
function check() { if(document.hasFocus() == canRefresh) return; canRefresh = !canRefresh; }
It works! Thanks again, guys!