Skip to content

Instantly share code, notes, and snippets.

@davidjpfeiffer
Last active March 30, 2021 18:29
Show Gist options
  • Save davidjpfeiffer/6c48aa7d4546ff693685d7e1e9870594 to your computer and use it in GitHub Desktop.
Save davidjpfeiffer/6c48aa7d4546ff693685d7e1e9870594 to your computer and use it in GitHub Desktop.
Lightweight Angular service detects when a user is inactive
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