Last active
March 30, 2021 18:29
-
-
Save davidjpfeiffer/6c48aa7d4546ff693685d7e1e9870594 to your computer and use it in GitHub Desktop.
Lightweight Angular service detects when a user is inactive
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { Injectable } from '@angular/core'; | |
import { fromEvent, merge } from 'rxjs'; | |
import { throttleTime } from 'rxjs/operators'; | |
@Injectable({ providedIn: 'root' }) | |
export class InactiveUserService { | |
public inactive: boolean; | |
private timer: NodeJS.Timer; | |
private activity = merge( | |
fromEvent(document, 'click'), | |
fromEvent(document, 'scroll'), | |
fromEvent(document, 'mousemove') | |
); | |
constructor() { | |
this.activity.pipe(throttleTime(5000)).subscribe(() => { | |
this.handleActivity(); | |
}); | |
} | |
private handleActivity() { | |
this.inactive = false; | |
if (this.timer) { | |
clearTimeout(this.timer); | |
} | |
this.waitForUserToBeInactive(); | |
} | |
private waitForUserToBeInactive() { | |
this.timer = setTimeout(() => this.inactive = true, 60000); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment