I am developing functionality similar to an auction, using jQuery, AJAX, PHP and mySQL.
Ajax accesses the server every second to get the most recent bid, and during this call we also get the remaining time from the server to keep all participants in sync.
I have two issues:
1) Occasionally the time remaining flickers back to the value of the previous time for a fraction of a second. Could this is to do with the asynchronous results getting out of sync?
Snippets of the relevant code:
function dotimer() {
updateScreen();
setTimeout('dotimer()',1000);
}
function updateScreen(){
$.ajax({
type : 'POST',
url : 'getinfo.php',
dataType : 'json',
data: { /* various params are passed to php */ },
success : function(data){
/* other info processed here...*/
$("#countdowntimer").html(data.secondsremaining);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {}
});
}
getinfo.php:
$return['secondsremaining'] = strtotime($end_time)-strtotime("now");
/* get other infor from database... */
echo json_encode($return);
(setTimeout and setInterval both had the same results.)
2) Is accessing the database every second excessive? I can’t see an alternative to ensure information is up-to-date. Is there a better way to do this?
The auction is for a relatively short period of time (30 min) and we do not expect any more than 10 participants.
Any advice/suggestions welcome, thanks!
I think that’s exactly your problem. As the requests are asynchronous, you cannot control the order that they are executed. You have to synchronize your requests and avoid multiple requests ie you can only do a new request if there aren’t pending requests, else you cannot control when the callback for each request is fired.