gpt4 book ai didi

php - 停止 JQuery 中的动画延迟

转载 作者:可可西里 更新时间:2023-11-01 01:04:43 25 4
gpt4 key购买 nike

我正在使用 PHP 和 JQuery 开发这个 CPU 监视器 - http://nereus.rikkuness.net/admin/cpu2.php

它的工作完全符合我的预期,只是遇到了一个小问题。由于使用轮询当前 CPU 使用率的命令,JQuery 调用值更新和更新实际到达有 1 秒的延迟。这样做的链式 react 是,当条形图设置动画时,它总是落后一秒钟,因为它第一次尝试调整大小时仍未收到新值,因此会根据收到的最后一个值自行调整大小。

谁能想出任何方法让我在值更新时立即设置动画,而不管实际收到值的时间如何?

谢谢你们,你们是最棒的! :)

如果不想在直播页面查看源码,代码如下:

var auto_refresh = setInterval(
function(){
height = 100;
$("#val1").load("cpu.php");
cpuUsage = $("#val1").html();
height = cpuUsage * 10;
barColor = "";

if(parseInt(height) < 500){
barColor = "green";
}else if(parseInt(height) > 800){
barColor = "red";
}else{
barColor = "#febf01";
}

$("#val2").animate({
width: parseInt(height),
backgroundColor: barColor
})
}, 1000);

最佳答案

使用.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);

仅供引用,我还进行了以下额外更改:

  1. 添加了 var 使您的变量成为局部变量,而不是隐式全局变量。
  2. 我在高度上提取了 parseInt(),所以它只在一个地方被调用,而不是 4 个地方。
  3. 我在应该始终使用的 parseInt() 上添加了基数参数。
  4. 删除不需要的高度变量的额外初始化。

我实际上会建议一个不同的实现,它在最后一次迭代完成之前不会为下一次迭代启动计时器。正如您现在所拥有的那样,如果您的 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();

关于php - 停止 JQuery 中的动画延迟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13943093/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com