如何知道用户当前是否正在使用Javascript读取页面?

Kar*_*arl 9 javascript ajax

我正在创建一个包含动态内容的网页,该网页通过AJAX轮询进入视图.页面JS偶尔会下载更新的信息,并在用户阅读其他信息时将其呈现在页面上.这种事情对带宽和处理时间来说代价很高.我希望在没有查看页面时暂停轮询.

我注意到我打开的大部分网页花费了大部分时间,或者在未查看的标签中.我希望能够暂停脚本,直到实际查看页面.

我不知道该怎么做,它似乎试图打破html DOM的沙箱并进入用户的系统.如果JS引擎不了解其渲染环境,则可能是不可能的.我从来没有见过不同的网站这样做(不是用户打算看到它......)

因此,我认为这是一个有趣的讨论问题.您如何编写一个CPU重的Web应用程序,以便在不使用时暂停?给用户一个暂停按钮是不可靠的,我希望它是自动的.

Pim*_*ger 4

你最好的解决方案是这样的:

 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.
  }    
 }
Run Code Online (Sandbox Code Playgroud)

stopAjaxUpdateFunction 应停止 AJAX 更新进度。