In order to implement a countdown timer that resets upon user action, you can utilize a host listener to track user interactions:
@HostListener('document:keyup', ['$event'])
@HostListener('document:click', ['$event'])
@HostListener('document:wheel', ['$event'])
resetTimer () {
// User action detected
}
The countdown timer functionality could be structured as follows:
endCount = new Subject();
// Define end time in minutes
private initTimer (endTime: number) {
const interval = 1000;
const duration = endTime * 60;
this.subscription = Observable.timer(0, interval)
.take(duration)
.subscribe(value => this.render((duration - +value) * interval),
err => { },
() => {
this.endCount.next();
});
}
private render (count) {
this.secondsDisplay = this.getSeconds(count);
this.minutesDisplay = this.getMinutes(count);
}
private getSeconds (ticks: number) {
const seconds = ((ticks % 60000) / 1000).toFixed(0);
return this.pad(seconds);
}
private getMinutes (ticks: number) {
const minutes = Math.floor(ticks / 60000);
return this.pad(minutes);
}
private pad (digit: any) {
return digit <= 9 ? '0' + digit : digit;
}
Listen for the endCount event to determine when the user has been inactive for a specific period.
To reset the timer:
resetTimer (newEndTime) {
this.clearTimer();
this.initTimer(newEndTime);
}
clearTimer () {
if (this.subscription) {
this.subscription.unsubscribe();
}
}
Here is an example implementation on Stackblitz: https://stackblitz.com/edit/angular-2rv3or