I am working on this CPU monitor using PHP and JQuery – http://nereus.rikkuness.net/admin/cpu2.php
It’s working exactly as I intend it to work with one slight problem. Due to the command used which polls the current CPU usage there is a delay from the JQuery calling for a value update and the update actually arriving of 1 second. The knock-on effect of this is that when the bar animates it’s always a second behind because the first time it tries to resize it still hasn’t received the new value and so resizes itself based on the last value it received.
Can anyone think of any way in which I can get it to animate as soon as the value updates, regardless of when the value is actually received?
Thanks guys, you’re the best! 🙂
Code is as follows if you don’t want to view source on the live page:
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);
Use the completion function in
.load()which will tell you exactly when$("#val1").load("cpu.php");has completed like this:FYI, I also made these additional changes:
varto make your variables be local variables, not implicit global variables.parseInt()on the height so it is only called in one place instead of 4 places.parseInt()which should always be used.I would actually suggest a different implementation that doesn’t start a timer for the next iteration until the last iteration is done. As you have it now, if your cpu.php call ever takes more than 1 second to respond, you will pile up multiple calls all in flight at once. Instead, you can start the next iteration’s timer when the previous one finished.