UNPKG

idle-detect

Version:

A TypeScript library for inactivity timer, which utilises `IdleDetector` API where possible or a fallback to `window.setTimeout` approach

80 lines (79 loc) 3.15 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.IdleDetect = exports.defaultNoop = exports.defaultNoLog = exports.defaultIdleTime = exports.defaultEventTypes = void 0; exports.defaultEventTypes = ['mousedown', 'touchstart', 'keypress']; /** 15 minutes by default */ exports.defaultIdleTime = 15 * 60 * 1000; const defaultNoLog = () => { }; exports.defaultNoLog = defaultNoLog; const defaultNoop = () => { }; exports.defaultNoop = defaultNoop; class IdleDetect { /** * @param idleSeconds Number of seconds for idle detection, 15 minutes by default * @param onIdle Event handler when user is idle for specified time * @param enableLogs * @param eventTypes */ constructor(idleSeconds = exports.defaultIdleTime, onIdle = exports.defaultNoop, enableLogs = false, eventTypes = exports.defaultEventTypes) { /** List of tracket event types, bubbled to `window` and used for timeout */ this.eventTypes = exports.defaultEventTypes; /** Idle timeout in milliseconds */ this.idleTime = exports.defaultIdleTime; /** Event handler when user is idle for specified time */ this.handleIdle = exports.defaultNoop; this.error = exports.defaultNoLog; this.log = exports.defaultNoLog; // [perf] Use debounce here? this.redoTimeout = () => { this.log('IdleDetect: redoTimeout()'); window.clearTimeout(this.timeout); this.timeout = window.setTimeout(() => { this.cleanupAndStop(); this.handleIdle(); }, this.idleTime); }; this.setIdleTime = (idleSeconds = exports.defaultIdleTime) => { this.log('IdleDetect: setIdleTime()', idleSeconds); this.idleTime = idleSeconds * 1000; }; this.setLogs = (enableLogs = false) => { if (enableLogs) { this.error = console.error; this.log = console.log; } else { this.error = exports.defaultNoLog; this.log = exports.defaultNoLog; } }; this.startTimeout = () => { this.log('IdleDetect: startTimeout()'); // Event listeners for (const eventType of this.eventTypes) { window.addEventListener(eventType, this.redoTimeout); } // Reset this.redoTimeout(); }; this.start = () => { if (!this.idleTime) { this.error('IdleDetect: idleTime is must be a positive number to start'); return; } this.startTimeout(); }; this.eventTypes = eventTypes; this.setIdleTime(idleSeconds); this.handleIdle = onIdle; this.setLogs(enableLogs); } cleanupAndStop() { this.log('IdleDetect: cleanupAndStop()'); window.clearTimeout(this.timeout); for (const eventType of this.eventTypes) { window.removeEventListener(eventType, this.redoTimeout); } } } exports.IdleDetect = IdleDetect;