Reputation: 1707
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, i.e. 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?
Upvotes: 1
Views: 476
Reputation: 161457
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.
Upvotes: 1