Signal-Desktop/js/modules/idle_detector.js

47 lines
989 B
JavaScript
Raw Normal View History

/* eslint-env browser */
2018-03-21 19:17:32 +00:00
const EventEmitter = require('events');
const POLL_INTERVAL_MS = 30 * 1000;
const IDLE_THRESHOLD_MS = 25;
2018-03-21 19:17:32 +00:00
class IdleDetector extends EventEmitter {
2018-03-21 19:17:32 +00:00
constructor() {
super();
this.handle = null;
this.timeoutId = null;
2018-03-21 19:17:32 +00:00
}
start() {
this._scheduleNextCallback();
2018-03-21 19:17:32 +00:00
}
stop() {
if (this.handle) {
cancelIdleCallback(this.handle);
2018-03-21 19:17:32 +00:00
}
if (this.timeoutId) {
clearTimeout(this.timeoutId);
}
}
_scheduleNextCallback() {
this.stop();
2018-03-23 14:11:01 +00:00
this.handle = window.requestIdleCallback((deadline) => {
const { didTimeout } = deadline;
const timeRemaining = deadline.timeRemaining();
const isIdle = timeRemaining >= IDLE_THRESHOLD_MS;
if (isIdle || didTimeout) {
this.emit('idle', { timestamp: Date.now(), didTimeout, timeRemaining });
}
this.timeoutId = setTimeout(() => this._scheduleNextCallback(), POLL_INTERVAL_MS);
});
2018-03-21 19:17:32 +00:00
}
}
module.exports = {
IdleDetector,
2018-03-21 19:17:32 +00:00
};