使用完成功能,.load()
其中将准确告诉您何时$("#val1").load("cpu.php");
完成,如下所示:
var auto_refresh = setInterval(
function(){
$("#val1").load("cpu.php", function() {
var cpuUsage = $("#val1").html();
var height = parseInt(cpuUsage * 10, 10);
var barColor = "";
if(height < 500){
barColor = "green";
}else if(height > 800){
barColor = "red";
}else{
barColor = "#febf01";
}
$("#val2").animate({
width: height,
backgroundColor: barColor
})
});
}, 1000);
仅供参考,我还进行了这些额外的更改:
- 添加
var
以使您的变量成为局部变量,而不是隐式全局变量。
- 我考虑了
parseInt()
高度,所以它只在一个地方而不是 4 个地方被调用。
parseInt()
我添加了应该始终使用的 radix 参数。
- 删除不需要的高度变量的额外初始化。
我实际上会建议一个不同的实现,它不会为下一次迭代启动计时器,直到最后一次迭代完成。正如你现在所拥有的,如果你的 cpu.php 调用需要超过 1 秒的时间来响应,你将一次堆积多个调用。相反,您可以在前一个迭代完成时启动下一个迭代的计时器。
var usageTimer;
var usageContinue = false;
function stopUsage() {
clearTimeout(usageTimer);
usageContinue = false;
}
// getUsage runs continuously until stopUsage is called
function getUsage() {
var start = new Date().getTime();
$("#val1").load("cpu.php", function() {
if (usageContinue) {
var cpuUsage = $("#val1").html();
var height = parseInt(cpuUsage * 10, 10);
var barColor = "";
if(height < 500){
barColor = "green";
}else if(height > 800){
barColor = "red";
}else{
barColor = "#febf01";
}
$("#val2").animate({
width: height,
backgroundColor: barColor
})
// start the next no sooner than 1 second from when the last one was started
var end = new Date().getTime();
// if the .load() call already took more than a second, then just start the next one now
if (end - start > 1000) {
getUsage();
} else {
// otherwise, start the next one 1 second after the previous one was started (to try to get one every second)
usageTimer = setTimeout(getUsage, end - start);
}
}
});
}
getUsage();