Reputation: 32331
I am displaying live news in my website and for that to get the latest data i am using setInterval for every 9 minutes as shown below
$(document).ready(function() {
displaylivenews();
setInterval(displaylivenews, 540000);
});
function displaylivenews() {
alert('calling ajax to getting latest data ');
}
All this works fine , my question is that , if the time is in between 7 Am to 9 AM , i want to call it more frequently that is for every 5 minutes ??
Is it possible to call setInterval based on time based ??
Upvotes: 0
Views: 65
Reputation: 34234
Answering your question, you can do the following:
function getRefreshPeriod()
{
var hour = new Date().getHours();
return (hour >= 7 && hour < 9) ? 300000 : 540000;
}
function displaylivenews() {
alert('calling ajax to getting latest data ');
setTimeout(displaylivenews, getRefreshPeriod());
}
setTimeout(displaylivenews, getRefreshPeriod());
I used setTimeout
in order to correctly handle "border" cases.
For example, if a user opens a page at 08:46 AM, he will get updates at 08:51 (5 minutes later), 08:56, 09:01, 09:10 (9 minutes later, because it is not a "prime time" anymore).
However, keep in mind that setInterval
and setTimeout
do not guarantee to be precise. It is a better idea to calculate the time of next updating, and rely on it.
Another important note: new Date()
will return the client's local time. So, actually, news will be updated more frequently between 7AM and 9AM of local time. If you have users from different time zones and want them to receive news more frequently between 7AM and 9AM in your time zone, then you may want to use getUTCHours
.
For example, I am located in GMT+6 time zone, and if I had this website, it would be:
var hour = new Date().getUTCHours();
return (hour >= 1 && hour < 3) ? 300000 : 540000;
because 1AM and 3AM UTC are 7 AM and 9AM in UTC+6.
Upvotes: 3