Signal-Desktop/js/modules/idle_detector.js

53 lines
1.1 KiB
JavaScript
Raw Normal View History

/* eslint-env browser */
2018-03-21 19:17:32 +00:00
const EventEmitter = require('events');
const POLL_INTERVAL_MS = 15 * 1000;
const IDLE_THRESHOLD_MS = 20;
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() {
console.log('Start idle detector');
this._scheduleNextCallback();
2018-03-21 19:17:32 +00:00
}
stop() {
console.log('Stop idle detector');
this._clearScheduledCallbacks();
}
_clearScheduledCallbacks() {
if (this.handle) {
cancelIdleCallback(this.handle);
2018-03-21 19:17:32 +00:00
}
if (this.timeoutId) {
clearTimeout(this.timeoutId);
}
}
_scheduleNextCallback() {
this._clearScheduledCallbacks();
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
};