Javascript 是否可以基于时间调用setInterval?
我在我的网站上显示实时新闻,为了获取最新数据,我每9分钟使用一次setInterval,如下所示Javascript 是否可以基于时间调用setInterval?,javascript,Javascript,我在我的网站上显示实时新闻,为了获取最新数据,我每9分钟使用一次setInterval,如下所示 $(document).ready(function() { displaylivenews(); setInterval(displaylivenews, 540000); }); function displaylivenews() { alert('calling ajax to getting latest data '); } 所有这些都很好,我的问题是,如果时间在
$(document).ready(function() {
displaylivenews();
setInterval(displaylivenews, 540000);
});
function displaylivenews() {
alert('calling ajax to getting latest data ');
}
所有这些都很好,我的问题是,如果时间在早上7点到9点之间,我想更频繁地打电话,即每5分钟一次
是否可以基于时间调用setInterval
回答您的问题,您可以执行以下操作:
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());
因为UTC+6的凌晨1点和凌晨3点是上午7点和上午9点。回答您的问题,您可以执行以下操作:
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());
因为UTC+6的凌晨1点和凌晨3点分别是上午7点和上午9点