Setinterval is stop working when tab is idle or working on another tab,

Viewed 130

I have created a solution for sessiontimeout popup, to check idle time I am using a setInterval as mentioned below

    // Increment the idle time counter every 1 second.
    idleInterval = setInterval(timerIncrement, 2000, (@warningShowDelayMinutes * 60), (@sessionTimeout * 60), @warningTimeLeft);

function timerIncrement(warningShowDelay, sessionTimeout) {
        idleTime++;
        console.log("before dialog open idleTime - :" + idleTime);
        if (idleTime >= warningShowDelay && idleTime <= sessionTimeout) {
            var isWarningPopupOpened = $('#session-expire-warning').dialog('isOpen');
            if (!isWarningPopupOpened) {
                $("#session-expire-warning").dialog("open");
                //console.log("before dialog after idleTime -:" + idleTime);
            }
        }
    }

but when we move to another tab/ another window, setInterval stops working, I also tried with requestAnimationFrame but it also stop working after we move to another tab or window as mentioned below.

var last = 0;
function timerIncrement(now) {
     if (!last || now - last >= 1000) {
        last = now;
        //createNewObject();
   
        idleTime++;
        console.log("before dialog open idleTime - :" + idleTime);
        if (idleTime >= (@warningShowDelayMinutes * 60) && idleTime <=  (@sessionTimeout * 60)) {
            var isWarningPopupOpened = $('#session-expire-warning').dialog('isOpen');
            if (!isWarningPopupOpened) {
                $("#session-expire-warning").dialog("open");
                console.log("before dialog after idleTime -:" + idleTime);
            }
        }
        }
        requestAnimationFrame(timerIncrement);
    }
    requestAnimationFrame(timerIncrement);

can anyone help on this to continue the setinetrval or requestAnimationFrame after tab switching ? I am new to javascripts

1 Answers

You can use the worker-timers NPM package to overcome this hurdle. It uses Web worker to prevent the timer(s) being throttled by the browser.

Related