Javascript/Jquery Refresh timer

2020-07-24 03:36发布

问题:

I have a simple system that refreshes a div every few seconds:

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

Now, because of what the content is, it is more likely to update on the hour, or at half past. (Though not always). What I'd like to do it make the system refresh MORE often between a few minutes before and after the hour (and half past), just to make it more precise.

Is this possible/how would I do it without stressing out the client's computer too much?

回答1:

Since the interval itself is going to be dynamic, you're going to have to use setTimeout instead.

Something like this (untested):

$(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);
});


回答2:

Use setTimeout instead of setInterval so you can dynamically alter the timing of the next interval. I'm not sure what the performance implications of creating and checking the Date() object ever millisec in the "Fast" period would be, but you could always tune that frequency up closer to every second if its an issue.

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();
});