Karl Karl - 1 year ago 68
Ajax Question

How to know if a page is currently being read by the user with Javascript?

I'm making a webpage with dynamic content that enters the view with AJAX polling. The page JS occasionally downloads updated information and renders it on the page while the user is reading other information. This sort of thing is costly to bandwidth and processing time. I would like to have the polling pause when the page is not being viewed.

I've noticed most of the webpages I have open spend the majority of their time minimized or in a nonviewed tab. I'd like to be able to pause the scripts until the page is actually being viewed.

I have no idea how to do it, and it seems to be trying to break out of the sandbox of the html DOM and reach into the user's system. It may be impossible, if the JS engine has no knowledge of its rendering environment. I've never even seen a different site do this (not that the user is intended to see it...)

So it makes for an interesting question for discussion, I think. How would you write a web app that is CPU heavy to pause when not being used? Giving the user a pause button is not reliable, I'd like it to be automatic.

Answer Source

Your best solution would be something like this:

 var inactiveTimer;
 var active = true;
 function setTimer(){
  inactiveTimer = setTimeOut("stopAjaxUpdateFunction()", 120000); //120 seconds
 document.onmouseover = function() { clearTimeout ( inactiveTimer ); 
  }; //clear the timer and reset it.
 function stopAjaxUpdateFunction(){
  //Turn off AJAX update
  active = false;   
 function resumeAjaxUpdate(){
  if(active == false){
   //Turn on AJAX update
   active = true;
   //do nothing since we are still active and the AJAX update is still on.

The stopAjaxUpdateFunction should stop the AJAX update progress.