I am trying to build a webapp that gets data from server and shows it to user. Script gets data from server every 10 seconds and if data has changed it alerts user. This is the code I'm using now, but it alerts every 10 second whether the data has changed or not.
So how do I need to alter my scipt to make it compare the old JSON and the new JSON and see if they are different, and if they are show alert before updating data shown to user?
$('#ListPage').bind('pageinit', function(event) {
getList1();
});
setInterval ( "getList1()", 10000 );
var old = "";
function getEmployeeList1() {
$.getJSON(serviceURL + 'getemployees.php?' + formArray, function(data) {
if(data != old){ // data from the server is not same as old
$('#nollalista li').remove();
keikka = data.key;
$.each(keikka, function(index, lista) {
$('#nollalista').append('<li><a href="employeedetails.html?id=' + lista.IND + '">' +
'<h4>' + lista.OSO + '</h4>' +
'<p>' + lista.AIKA + '</p>' +'</a></li>');
});
$('#nollalista').listview('refresh');
if(old != "")
alert("New data!");
old = data;
}
});
}
setInterval()orsetTimeout(). Doing so is as bad as usingeval()and it results in unreadable and possibly insecure code as soon as you use variables since you need to insert them into the string instead of passing the actual variable. The proper solution issetInterval(function() { /* your code *) }, msecs);. The same applies tosetTimeout(). If you just want to call a single function without any arguments, you can also pass the function name directly:setInterval(someFunction, msecs);(note that there are no()behind the function name)