UNPKG

smart-idle

Version:

Lightweight browser library to detect user inactivity with event dispatching

91 lines (90 loc) 2.01 kB
// src/SmartIdle.ts var SmartIdle = class { constructor(options = {}) { this._timer = null; this._idle = false; this._paused = false; this._events = []; this.timeout = options.timeout || 6e4; this.onIdle = options.onIdle || (() => { }); this.onActive = options.onActive || (() => { }); this._events = options.events || [ "mousemove", "keydown", "scroll", "touchstart", "visibilitychange" ]; this._handleEvent = this._handleEvent.bind(this); } start() { this._events.forEach((e) => window.addEventListener(e, this._handleEvent)); this._resetTimer(); } stop() { this._events.forEach((e) => window.removeEventListener(e, this._handleEvent)); if (this._timer) clearTimeout(this._timer); } pause() { this._paused = true; if (this._timer) clearTimeout(this._timer); } resume() { if (!this._paused) return; this._paused = false; this._resetTimer(); } isIdle() { return this._idle; } triggerIdle() { if (!this._idle) { this._idle = true; this.onIdle(); window.dispatchEvent(new CustomEvent("idle")); } } triggerActive() { if (this._idle) { this._idle = false; this.onActive(); window.dispatchEvent(new CustomEvent("active")); this._resetTimer(); } } destroy() { this.stop(); this._idle = false; this._paused = false; this._timer = null; } _handleEvent() { if (this._paused) return; if (this._idle) { this._idle = false; this.onActive(); window.dispatchEvent(new CustomEvent("active")); } this._resetTimer(); } _resetTimer() { if (this._timer) clearTimeout(this._timer); if (this._paused || document.hidden) return; this._timer = setTimeout(() => { this._idle = true; this.onIdle(); window.dispatchEvent(new CustomEvent("idle")); }, this.timeout); } }; export { SmartIdle };