0

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.

Tracy Zhou
  • 714
  • 1
  • 7
  • 11

2 Answers2

1

You could avoid using a 3rd party lib and use something among these lines here

You have few options with the widnow.focus/window.blur as well as document.hidden. It might end up being cleaner and less dependent on another lib. Hope this helps.

Akrion
  • 18,117
  • 1
  • 34
  • 54
1

Is this what you need?

$(window).blur(function() {
  isPageActive = false;
});

$(window).focus(function() {
  isPageActive = true;
});
Chaska
  • 3,165
  • 1
  • 11
  • 17