2018-03-21 19:45:39 +00:00
|
|
|
/* eslint-env browser */
|
|
|
|
|
2018-03-21 19:17:32 +00:00
|
|
|
const EventEmitter = require('events');
|
|
|
|
|
|
|
|
|
2018-03-23 14:17:06 +00:00
|
|
|
const POLL_INTERVAL_MS = 30 * 1000;
|
2018-03-21 19:45:39 +00:00
|
|
|
const IDLE_THRESHOLD_MS = 25;
|
2018-03-21 19:17:32 +00:00
|
|
|
|
2018-03-21 19:21:38 +00:00
|
|
|
class IdleDetector extends EventEmitter {
|
2018-03-21 19:17:32 +00:00
|
|
|
constructor() {
|
|
|
|
super();
|
2018-03-21 19:45:39 +00:00
|
|
|
this.handle = null;
|
|
|
|
this.timeoutId = null;
|
2018-03-21 19:17:32 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
start() {
|
2018-03-21 19:45:39 +00:00
|
|
|
this._scheduleNextCallback();
|
2018-03-21 19:17:32 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
stop() {
|
2018-03-21 19:45:39 +00:00
|
|
|
if (this.handle) {
|
|
|
|
cancelIdleCallback(this.handle);
|
2018-03-21 19:17:32 +00:00
|
|
|
}
|
|
|
|
|
2018-03-21 19:45:39 +00:00
|
|
|
if (this.timeoutId) {
|
|
|
|
clearTimeout(this.timeoutId);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
_scheduleNextCallback() {
|
|
|
|
this.stop();
|
2018-03-23 14:11:01 +00:00
|
|
|
this.handle = window.requestIdleCallback((deadline) => {
|
2018-03-21 19:45:39 +00:00
|
|
|
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 = {
|
2018-03-21 19:21:38 +00:00
|
|
|
IdleDetector,
|
2018-03-21 19:17:32 +00:00
|
|
|
};
|