I am using a setTimeout loop pulling data from database every 5 seconds. Here is part of my javascript:
(function setDailystats() {
$.ajax({
type: "GET",
contentType: 'application/json',
url: '@Url.Action("GetDailyStats", "myControllerName")',
async: true,
success: function (data) {
$("#todayAppts").text(data.appts);
$("#todayAlerts").text(data.alerts);
console.log("Update daily stats");
setTimeout(setDailystats, 5000);
}
});
}());
The problem is the loop continue running even when I am away from the page. I want to stop the loop when page inactive, restart the loop when page active.
I have tried to use ifvisible.js:
var isPageActive = true;
ifvisible.setIdleDuration(10);
ifvisible.on("idle", function () {
isPageActive = false;
});
ifvisible.on("wakeup", function () {
isPageActive = true;
});
(function setDailystats() {
if (isPageActive) {
$.ajax({
type: "GET",
contentType: 'application/json',
url: '@Url.Action("GetDailyStats", "myControllerName")',
async: true,
success: function (data) {
$("#todayAppts").text(data.appts);
$("#todayAlerts").text(data.alerts);
console.log("Update daily stats");
}
});
};
console.log("Check page activity");
setTimeout(setDailystats, 5000);
}());
It works fine. I am just wondering if there is any other better way to do it. There is still stuff (ifvisible.js, check every 5 seconds ...) running in the background all the time.