我的网页上有需要每隔几分钟刷新一次的数据网格。当 Javascript 计时器到期时,使用 PHP 从 mysql 数据库查询数据。数据导入后,需要对其进行样式设置以使问题更容易被发现,因此我触发了另一个计时器,该计时器每 2.5 秒翻转一次,总共翻转 3 次,然后关闭。我想出了这个解决方案,因为数据网格没有立即填充,所以在查询后立即运行它会导致它丢失大部分数据。
问题: 1) 最大的问题是如果电脑进入休眠状态时网页在浏览器中保持打开状态,则会出现几个空警报。鉴于有多少人将在工作中使用该网站,这种行为是完全不能接受的。我没主意了。
2) 我希望有更好的方法来处理导入时的数据,这样我就不必在刷新后 $("td").each() 整个页面。我使用的是 dhtmlx 库中的组件,因此打开函数并在内部处理这个问题有点困难。对数据进行后处理是我真正能做的一切,但我对想法持开放态度。
变量声明和初始定时器设置:
//Set a timer to refresh all grid data every 4 minutes
var RefreshDataTimer = setInterval(timerMethod, 240000);
//Set an initial timer for the box coloring method
var RefreshBoxTimer = setInterval(boxMethod, 3000);
网格数据刷新计时器处理程序:
//Every 2.5 minutes this function will reload all of the grid data.
//It also triggers the boxMethod function.
function timerMethod() {
$("#UpdateStatus_Div").fadeIn(300).delay(1000).fadeOut(300);
RunStatusGrid.clearAndLoad("data/RunStatus.php");
CmdlineGrid.clearAndLoad ("data/CmdlineDataGet.php");
Results0Grid.clearAndLoad ("data/Results0Data.php");
Results1Grid.clearAndLoad ("data/Results1Data.php");
Results2Grid.clearAndLoad ("data/Results2Data.php");
Results3Grid.clearAndLoad ("data/Results3Data.php");
RefreshBoxTimer = setInterval(boxMethod, 2500);
}
网格数据样式计时器处理程序:
//This function searches all of the grids for ERROR/FAIL/SKIP/WARN and changes
//the cell background colors to clearly show where there are issues.
//It will only run 3 times because it is CPU intensive. The 2.5 second delay is because
//the clearAndLoad functions are run as background tasks and don't complete immediately.
var BoxCounter = 0;
function boxMethod() {
BoxCounter++;
if(BoxCounter >= 4) {
BoxCounter = 0;
clearInterval(RefreshBoxTimer);
}
$("td").each(function(index) {
if( (this.innerHTML == "ERROR") || (this.innerHTML == "FAIL")) {
this.style.backgroundColor = "red";
this.style.fontWeight = "bold";
} else if ( (this.innerHTML == "SKIP") || (this.innerHTML == "WARN") ) {
this.style.backgroundColor = "yellow";
this.style.fontWeight = "bold";
}
} );
}
如有任何帮助,我们将不胜感激。
最佳答案
使用 setTimeout
而不是 setInterval
,并在每次调用回调时重置计时器。
setInterval
的问题在于,如果计算机忙于做其他事情,回调最终可能会“堆积起来”,因此它们会同时触发。
关于计算机从 sleep 状态恢复后,Javascript 计时器会导致过多警报,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9722155/