I am new to jQuery and want to use it to retrieve data from a server every 3 seconds. The web server sends data every 3 seconds in JSON format. The JSON data contains a numerical array field { “samples” : [10,15,-7,19,34,…] }. I wrote the following jQuery ajax request to retrieve data from the server every 3 seconds:
function getData() {
$.ajax({
url : 'http://example.com',
type: 'GET',
success : function(data) {
myData = data.samples;
setTimeout(getData, 3000);
},
dataType : 'json'
});
return myData;
}
However, due to timing jitter, the data sent from the server may not get updated precisely at every 3 seconds. So how should I write the jQuery ajax request to avoid the possible data discontinuity? That is, I want the returned myData contains all fresh new data array elements from each getData() call and does not contain duplicated or missing data samples due to possible timing jitter.
Send the last timestamp that the data was updated on the server along with the other JSON array. Then, when it is time to request data again using your jQuery call, check the timestamp against what you already have. This will give you a way to know if it is the same data, or if it has been refreshed.