idle-manager-js
Version:
Detect user inactivity and track active state with ease.
62 lines (61 loc) • 1.88 kB
JavaScript
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var IdleManager = /** @class */function () {
function IdleManager(_a) {
var _b = _a.idleTime,
idleTime = _b === void 0 ? 60000 : _b,
onIdle = _a.onIdle,
onActive = _a.onActive,
_c = _a.events,
events = _c === void 0 ? ["mousemove", "keydown", "mousedown", "touchstart", "touchmove", "visibilitychange", "scroll", "resize"] : _c;
this.idleTime = idleTime;
this.onIdle = onIdle;
this.onActive = onActive;
this.timer = null;
this.isIdle = false;
this.events = events;
this.handleEvent = this.resetTimer.bind(this);
}
IdleManager.prototype.start = function () {
var _this = this;
this.events.forEach(function (event) {
return window.addEventListener(event, _this.handleEvent);
});
this.resetTimer();
};
IdleManager.prototype.stop = function () {
var _this = this;
this.events.forEach(function (event) {
return window.removeEventListener(event, _this.handleEvent);
});
if (this.timer) clearTimeout(this.timer);
};
IdleManager.prototype.resetTimer = function () {
var _this = this;
var _a;
if (document.visibilityState === "hidden") {
this.triggerIdle();
return;
}
if (this.timer) clearTimeout(this.timer);
if (this.isIdle) {
this.isIdle = false;
(_a = this.onActive) === null || _a === void 0 ? void 0 : _a.call(this);
}
this.timer = setTimeout(function () {
return _this.triggerIdle();
}, this.idleTime);
};
IdleManager.prototype.triggerIdle = function () {
var _a;
if (!this.isIdle) {
this.isIdle = true;
(_a = this.onIdle) === null || _a === void 0 ? void 0 : _a.call(this);
}
};
return IdleManager;
}();
var _default = exports["default"] = IdleManager;