Skip to content

Instantly share code, notes, and snippets.

@barraponto
Last active April 3, 2024 11:17
Show Gist options
  • Select an option

  • Save barraponto/4547ef5718fd2d31e5cdcafef0208096 to your computer and use it in GitHub Desktop.

Select an option

Save barraponto/4547ef5718fd2d31e5cdcafef0208096 to your computer and use it in GitHub Desktop.
ES6+ event-based browser idle timer.
const DOCUMENT_EVENTS = [
'mousemove', 'mousedown', 'click',
'touchmove', 'touchstart', 'touchend',
'keydown', 'keypress'
];
export class IdleTimer {
constructor(onIdleTimeout, timeout) {
this.onIdleTimeout = onIdleTimeout;
this.timeout = timeout;
this.timer = null;
this.active = false;
this.resetTimer = this.resetTimer.bind(this);
}
activate() {
if (!this.active) { this.bindEvents(); }
this.timer = setTimeout(this.onIdleTimeout, this.timeout);
this.active = true;
}
deactivate() {
if (this.active) { this.unbindEvents(); }
clearInterval(this.timer);
this.active = false;
}
resetTimer() {
clearInterval(this.timer);
this.activate();
}
bindEvents() {
window.addEventListener(
'scroll', this.resetTimer, { capture: true, passive: true});
window.addEventListener('load', this.resetTimer);
DOCUMENT_EVENTS.forEach(
eventType => document.addEventListener(eventType, this.resetTimer));
}
unbindEvents() {
// remove only checks capture
window.removeEventListener( 'scroll', this.resetTimer, { capture: true });
window.removeEventListener('load', this.resetTimer);
DOCUMENT_EVENTS.forEach(
eventType => document.removeEventListener(eventType, this.resetTimer));
}
}
@barraponto

barraponto commented Jul 29, 2021

Copy link
Copy Markdown
Author

Usage:

import { IdleTimer } from './idletime';

const onTimeout = () => console.log('time is up!');
const idletimer = new IdleTimer(onTimeout, 7000);

idletimer.activate();

@DarioGHub

DarioGHub commented May 13, 2023

Copy link
Copy Markdown

Thanks Capi,
Little typo in Usage: ./idletimer could be ./idletime.
I was looking to reduce power consumption of my app when the user was absent.

@undfndusr

Copy link
Copy Markdown

thx

@Romick2005

Copy link
Copy Markdown

Does it really works as expected setting timeout with setTimeout and clearing with clearInterval not clearTimeout?

@Romick2005

Copy link
Copy Markdown

How about adding capture phase as true? Smth like document.addEventListener(eventType, this.resetTimer, true)?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment