Javascript / Jquery刷新计时器

时间:2010-01-02 17:04:59

标签: javascript jquery setinterval

我有一个简单的系统,每隔几秒刷新一次div:

$(document).ready(function() {
         $("#nownext").load("response.php");
       var refreshId = setInterval(function() {
          $("#nownext").load('response.php?randval='+ Math.random());
       }, 20000);
    });

现在,由于内容是什么,它更有可能在一小时或一半时更新。 (虽然不总是)。我想做的是让系统在小时前后几分钟(以及过去一半)之间更频繁地刷新,以使其更加精确。

这是否可行/如何在不过分强调客户端计算机的情况下进行此操作?

2 个答案:

答案 0 :(得分:1)

使用setTimeout而不是setInterval,这样您就可以动态地改变下一个间隔的时间。我不确定在“快速”时段创建和检查Date()对象的性能影响是什么,但是如果它出现问题,你总是可以将频率调整到接近每秒。

start_timer = function(timing) {
   var timer, d = new Date(), min = d.getMinutes(),
     timeout = 20000; /* slow timeout */
   if((min >= 28 && min <= 30) || min >= 58) {
     timeout = 100; /* fast timeout */
   }
   timer = setTimeout(start_timer, timeout);
   // Call your code here.
};

$(document).ready(function() {
    start_timer();
});

答案 1 :(得分:0)

由于间隔本身是动态的,因此您将不得不使用setTimeout

像这样(未经测试):

$(document).ready(function() {
    $("#nownext").load('response.php?randval='+ Math.random());
    var minutes = new Date().getMinutes(), interval = 60*10*1000; // default 10 mins
    if (minutes <= 10 || (minutes > 30 && minutes < 35) || minutes > 50) {
        // update once-per-minute if within the first/last 10mins of the hour, or 5mins within the half hour
        interval = 60*1000;
    }
    setTimeout(arguments.callee, interval);
});
相关问题