I have the following jQuery function that I’m using to display a timer on a page:
function update() {
$.ajax({
type: 'POST',
url: 'check_time.php',
data: 'checktime=true',
timeout: 0,
success: function(data) {
$(".time_remaining").html(data);
window.setTimeout(update, 1000);
var time = data;
if(time<=0)
{
$(".time_remaining").html("Reloading the page now.");
refresh();
}
else
{
$(".time_remaining").html("There are "+data+" seconds left." );
}
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
$("#notice_div").html('Error contacting server. Retrying in 60 seconds.');
window.setTimeout(update, 60000);
}
});
};
As you can see, it’s actually running a script that calculates how much time is remaining until a refresh is called (with the refresh() function). I feel this is a bit intensive because it’s calling every second, but I feel it’s important at the same time to have synchrony in the Ajax because if the refresh() function is called too early the page stops running in sync.
How can I make it that the timer is still always decreasing in time, but only synchronises with the server every 30 seconds or so?
Precision is really important for this application.
Use a variable
remainingTimeto store the remaining time:Update with ajax:
Continuously update:
Countdown:
Continuously countdown:
NOTE: It might be the case that you want to
setTimeoutinside thesuccesshandler, as you already did, and a longer timeout in theerrorhandler. But this should do the trick for decoupling the updating from the display.You definitely should use
setIntervalfor the countdown though, becausesetIntervaltries to trigger with that exact interval, whereassetTimeoutwill cause drift, that is, if it takes 10ms to update the DOM, the next call will only occur after 1010ms, and so on. WithsetInterval, this is not the case because the browser will do its best to actually trigger that function every 1000 ms.