I am facing a scenario where I have a webpage featuring a countdown alongside some dynamic data refreshed via AJAX. To optimize server load, I found a clever solution by adjusting the AJAX refresh interval based on the time remaining in the countdown, following guidance from
Specifically, to achieve a refresh rate of one minute when less than a day remains on the countdown and a rate of 5 minutes for over a day left, my implementation looks something like this:
var doStuff = function () {
// Perform actions
var remainingTime = JSONData.restTime;
if(remainingTime > one day) {
setTimeout(doStuff, 300000);
} else {
setTimeout(doStuff, 60000);
}
};
setTimeout(doStuff, 60000);
The "remainingTime" variable is derived from the JSON utilized for refreshing the content. Although it functions properly, I am seeking an enhancement. The initial AJAX call currently occurs after one minute of loading the page (as per the last "SetTimeout" in the code). Ideally, I aim to align this initial call with the remaining time—having it execute after 5 minutes if more than a day is left and after 1 minute for less than a day.
How can I synchronize the first AJAX call with the remaining time?