I have
- 1-many units in the database
- Each unit has it’s own update time in seconds
- Webpage that has dynamic contents
- Currently there is auto-refresh (2minutes) embedded see below every time it’s called
function refreshPage(){
minutes = 2;
seconds = 0;
interval=120000;
getCheckedUnits(); //call to function that checks and updates stuff
}
function timedRefresh(timeoutPeriod) {
//refreshPage();
setInterval(refreshPage, timeoutPeriod);
countdown('countdown');
}
var interval;
var minutes = 2;
var seconds = 0;
function countdown(element) {
interval = setInterval(function() {
var el = document.getElementById(element);
if(seconds == 0) {
if(minutes == 0) {
el.innerHTML = "Waiting for refresh";
clearInterval(interval);
return;
} else {
minutes--;
seconds = 60;
}
}
if(minutes > 0) {
var minute_text = minutes + (minutes > 1 ? ' minutes' : ' minute');
} else {
var minute_text = '';
}
var second_text = seconds > 1 ? 'seconds' : 'second';
el.innerHTML = 'Page will auto-refresh in: ' + minute_text + ' ' + seconds + ' ' + second_text + ' remaining';
seconds--;
}, 1000);
}
What I need to do, it to make it transparent to user and call update based on the need (I have value that is set in the database).
As a solution (in JS-Ajax), I can use the same timer that I have above (set it to 5 seconds) and create an array with objects that store id, last update time and next update time. Then I can update each object only when current time is more that next update time.
Or I can approach this method via cron-job.
I have never done this before and I would like to hear opinions that based on experience. What would be the best option?
Your scheme of fetching last update times and comparing them before fetching the much larger data is a perfectly valid approach to this problem, but there are others you can consider. In particular, you are trying to achieve is called server push. Using the last-update timestamps can approximate this, but alternative techniques like long polling and (in the future/some browsers) WebSockest are some alternatives.
Here is a better writeup to a similar question.