3

I have written code to display countdown timer using sweet alert popup when user is idle (using ng-idle library). After countdown timer is 0, user will be auto logged out. For decreasing countdown timer I am using setInterval function (which is causing the issue).

       var 
       closeInSeconds = Idle.getTimeout(), //this will fetch the auto logout time. In my case it is 20 seconds
       displayText = "Your session is about to expire in #1 seconds, Do you want to reset the session?",
       timer;

        timer = setInterval(function() {
            closeInSeconds--;
            if (closeInSeconds <= 0) {
                clearInterval(timer);
            }
            $('.sweet-alert > p').text(displayText.replace(/#1/, closeInSeconds));
        }, 1000);

        swal({
        title: "Alert",
        text: displayText.replace(/#1/, closeInSeconds),
        type: "warning",
        showCancelButton: true,
        confirmButtonColor: "#DDDDD",
        confirmButtonText:  "RESET",
        cancelButtonText: "NO"
        },

The above code is working absolutely fine when browser tab is active or user is idle but still on the tab. The peculiar issue arises when browser tab is minimized and idle warning popup comes on the screen. When I minimize the window and comes back to it, the timer seems to be showing the wrong value. On popup it sometimes show you have 10 seconds to logout but in actual it logs out within next 2-3 seconds. It means there is some issue with the setInterval function which is why it is not showing the exact countdown value when window is minimized. The auto logout feature is handled by IdleTimeout function of ng-idle library which works correctly and logs out the user when 20 seconds are over, whereas in popup it still shows time is remaining.

James Z
  • 12,209
  • 10
  • 24
  • 44
  • See answer here https://stackoverflow.com/q/5927284/ – belykh Mar 27 '21 at 05:07
  • 1
    Recommended watching: [JavaScript counters the hard way - HTTP 203](https://www.youtube.com/watch?v=MCi6AZMkxcU). You might also be interested in [Scheduling Tasks - HTTP 203](https://www.youtube.com/watch?v=8eHInw9_U8k). – Theraot Mar 27 '21 at 22:56
  • 1
    Does this answer your question? [How can I make setInterval also work when a tab is inactive in Chrome?](https://stackoverflow.com/questions/5927284/how-can-i-make-setinterval-also-work-when-a-tab-is-inactive-in-chrome) – Dexygen Mar 27 '21 at 23:14

0 Answers0