刷新给定时间范围的页面

时间:2012-02-07 05:58:54

标签: javascript

我有一个网站,我希望在每天的给定时间范围内每五分钟重新加载一次。时间,如每五分钟上午9:00至凌晨12:00。我该怎么做?

    function refreshAt(hours, minutes, seconds) {
    var now = new Date();
    var then = new Date();

    if(now.getHours() > hours ||
       (now.getHours() == hours && now.getMinutes() > minutes) ||
        now.getHours() == hours && now.getMinutes() == minutes && now.getSeconds() >= seconds) {
        then.setDate(now.getDate() + 1);
    }
    then.setHours(hours);
    then.setMinutes(minutes);
    then.setSeconds(seconds);

    var timeout = (then.getTime() - now.getTime());
    setTimeout(function() { window.location.reload(true); }, timeout);
}refreshAt(15,35,0); //Will refresh the page at 3:35pm

以下仅适用于给定时间

2 个答案:

答案 0 :(得分:0)

试试这个。

function set_timer()
{
 var var from = 9, to = 12, every = 5, now = new Date();

 if (now.getHours()<from) // prepare to run at 'from' hours exactly
    setTimeout(refresh_me, from * 3600 * 1000 - 
      ((now.getHours() * 60 + now.getMinutes()) * 60 + now.getSeconds()) * 1000);

 // run 'every' period between 'from' and 'to'
 if (now.getHours()>=from && now.getHours()<to) 
    setTimeout(refresh_me, every * 60 * 1000);

 if (now.getHours()>=to) // prepare for tomorrow's run at 'from'
 { 
    var tomorrow = new Date(now.getFullYear(), now.getMonth(), 
                            now.getDate() + 1, 0, 0, 0);
    setTimeout(refresh_me, 
               from * 3600 * 1000 + tomorrow.getTime() - now.getTime());
 }
}

function refresh_me()
{
 if ((new Date()).getHours()<to) // check the time between 12:00 and 12:05
    window.location.reload(true);
 else
    set_timer();  // reset timer if function is called between 12:00 and 12:05
}

set_timer();

答案 1 :(得分:0)

    var startTime = new Date(2000,1,1,9,30);
var endTime = new Date(2000,1,1,15,30);
window.setInterval(function()
{
    if(new Date().toLocaleTimeString() >= startTime.toLocaleTimeString() &&
        new Date().toLocaleTimeString() <= endTime.toLocaleTimeString() )
        window.location.reload(true);
}, 5 * 60 * 1000)