简体   繁体   中英

AJAX refresh with adaptive time interval

I have a page which includes a countdown and some data on it which I refresh with AJAX. In order to reduce load on the server, I made the AJAX refresh interval dependent on the remaining time of the countdown following instructions on http://reallifejs.com/brainchunks/repeated-events-timeout-or-interval/

For instance to have a refresh interval of one minute if remaining time is less than a day and refresh interval of 5 minutes if remaining time is greater than a day I have something like this:

var doStuff = function () {
    // Do stuff
    var remainingTime = JSONData.restTime;

    if(remainingTime > one day) {
        setTimeout(doStuff, 300000);
    } else {
        setTimeout(doStuff, 60000);
    }
};

setTimeout(doStuff, 60000);

The "remainingTime" is taken from the JSON which is used for the refresh. Now everything works fine. Still I would like to make one improvement, as the first AJAX call is done one minute after loading the page (based on the last "SetTimeout" in the code above). Ideally I would make this first call dependent on the rest time in the same way, ie first call after 5 minutes if more than one day left and first call after 1 minute if less than one day left.

How can I make this depend on the remaining time?

Instead of calling setTimeout initially, can't you just call doStuff?

var doStuff = function () {
  // Do stuff
  var remainingTime=JSONData.restTime;
  if(remainingTime>one day) {
    setTimeout(doStuff, 300000);
  } else {
    setTimeout(doStuff, 60000);
  }
};

doStuff();

Or if JSONData is not loaded yet, call doStuff from the first AJAX success callback.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM