Switch to using requestIdleCallback
Example: https://developer.mozilla.org/en-US/docs/Web/API/Background_Tasks_API#Example
This commit is contained in:
parent
d13668544d
commit
09ee2d4ea2
1 changed files with 25 additions and 18 deletions
|
@ -1,36 +1,43 @@
|
||||||
const desktopIdle = require('desktop-idle');
|
/* eslint-env browser */
|
||||||
|
|
||||||
const EventEmitter = require('events');
|
const EventEmitter = require('events');
|
||||||
|
|
||||||
|
|
||||||
const POLL_INTERVAL = 10; // seconds
|
const POLL_INTERVAL_MS = 10 * 1000;
|
||||||
const IDLE_THRESHOLD = POLL_INTERVAL;
|
const IDLE_THRESHOLD_MS = 25;
|
||||||
|
|
||||||
class IdleDetector extends EventEmitter {
|
class IdleDetector extends EventEmitter {
|
||||||
constructor() {
|
constructor() {
|
||||||
super();
|
super();
|
||||||
this.intervalId = null;
|
this.handle = null;
|
||||||
|
this.timeoutId = null;
|
||||||
}
|
}
|
||||||
|
|
||||||
start() {
|
start() {
|
||||||
this.stop();
|
this._scheduleNextCallback();
|
||||||
this.intervalId = setInterval(() => {
|
|
||||||
const idleDurationInSeconds = desktopIdle.getIdleTime();
|
|
||||||
const isIdle = idleDurationInSeconds >= IDLE_THRESHOLD;
|
|
||||||
if (!isIdle) {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
this.emit('idle', { idleDurationInSeconds });
|
|
||||||
|
|
||||||
}, POLL_INTERVAL * 1000);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
stop() {
|
stop() {
|
||||||
if (!this.intervalId) {
|
if (this.handle) {
|
||||||
return;
|
cancelIdleCallback(this.handle);
|
||||||
}
|
}
|
||||||
|
|
||||||
clearInterval(this.intervalId);
|
if (this.timeoutId) {
|
||||||
|
clearTimeout(this.timeoutId);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
_scheduleNextCallback() {
|
||||||
|
this.stop();
|
||||||
|
this.handle = 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);
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
Loading…
Add table
Add a link
Reference in a new issue