Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 892
Karl Avatar asked Feb 03 '23 12:02

Karl


2 Answers

Your best solution would be something like this:

 var inactiveTimer;
 var active = true;
 function setTimer(){
  inactiveTimer = setTimeOut("stopAjaxUpdateFunction()", 120000); //120 seconds
 }
 setTimer();
 document.onmouseover = function() { clearTimeout ( inactiveTimer ); 
                                     setTimer(); 
                                     resumeAjaxUpdate();
  }; //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;
  }else{
   //do nothing since we are still active and the AJAX update is still on.
  }    
 }

The stopAjaxUpdateFunction should stop the AJAX update progress.

like image 176
Pim Jager Avatar answered Apr 09 '23 18:04

Pim Jager


How about setting an "inactivity timeout" which gets reset every time a mouse or keyboard event is received in the DOM? I believe this is how most IM programs decide that you're "away" (though they do it by hooking the input messages at the system-wide level)

like image 36
jlew Avatar answered Apr 09 '23 20:04

jlew