如何知道,如果一个页面正在被支持JavaScript的用户阅读?页面、用户、JavaScript

2023-09-11 00:48:20 作者:泪了

我正在与进入与AJAX轮询查看动态内容的网页。在网页的JS偶尔下载的更新信息,并呈现在页面上,而用户正在阅读的其他信息。这样的事情是昂贵的带宽和处理时间。我想有投票暂停时,页面不被查看。

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.

我注意到大多数我都开了网页的花多数或他们的时间最小化,在nonviewed标签。我希望能够暂停脚本直到页面实际上是被观看。

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.

我不知道该怎么做,似乎是想打出来的HTML DOM的沙箱,并深入到用户的系统。这可能是不可能的,如果在JS引擎并不知道其再现环境的。我从来没有见过一个不同的网站做到这一点(不是用户打算看到它... ...)

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...)

因此​​,它是为讨论的一个有趣的问题,我想。你会如何​​编写一个Web应用程序是CPU重不使用时暂停?给用户一个暂停按钮是不可靠的,我想它是自动的。

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.

推荐答案

您最好的解决办法是这样的:

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.
  }    
 }

在stopAjaxUpdateFunction应停止AJAX更新的进展。

The stopAjaxUpdateFunction should stop the AJAX update progress.