bearnithi / bn-ng-idle

Angular user idle detector service
28 stars 11 forks source link

How to achieve idle state when system goes to sleep? #9

Open ShradhaRao opened 4 years ago

ShradhaRao commented 4 years ago

Thanks for the library, works well when the system is on. However, when the system goes to sleep, the timer is paused and starts executing when the system is back on. Is there a way to achieve and log out when the idle time is passed out while the system is asleep?

Thanks!

augoisms commented 4 years ago

I needed the same thing. The approach I took was to write the current time to localStorage and compare the current time against the cached time. This also has the side benefit of syncing multiple tabs together. If you have your site open in multiple tabs an idle tab won't sign out your active one.

my startTimer method now looks something like this:

private startTimer() {
    localStorage.setItem('idleTimeout', Date.now());

    // run timer every 1 second and check if we've reached timeout
    this.timer$ = timer(1000, 1000).subscribe((res) => {
        // check cached time in case another tab was active
        const cachedTime = parseInt(localStorage.getItem('idleTimeout')) || Date.now();

        // idle true
        if (Date.now() - cachedTime > this.timeoutMilliSeconds) {
            this.expired$.next(true);
        }
        // idle false   
        else {
            this.expired$.next(false);
        }         
    });
}