signal-desktop/ts/IdleDetector.ts

55 lines
1.4 KiB
TypeScript
Raw Normal View History

// Copyright 2018-2022 Signal Messenger, LLC
2020-10-30 20:34:04 +00:00
// SPDX-License-Identifier: AGPL-3.0-only
2021-12-10 23:20:24 +00:00
import EventEmitter from 'events';
import * as log from './logging/log';
import { clearTimeoutIfNecessary } from './util/clearTimeoutIfNecessary';
2018-03-21 19:17:32 +00:00
const POLL_INTERVAL_MS = 5 * 1000;
const IDLE_THRESHOLD_MS = 20;
2018-03-21 19:17:32 +00:00
2021-12-10 23:20:24 +00:00
export class IdleDetector extends EventEmitter {
private handle: undefined | ReturnType<typeof requestIdleCallback>;
private timeoutId: undefined | ReturnType<typeof setTimeout>;
2018-03-21 19:17:32 +00:00
2021-12-10 23:20:24 +00:00
public start(): void {
log.info('Start idle detector');
this.scheduleNextCallback();
2018-03-21 19:17:32 +00:00
}
2021-12-10 23:20:24 +00:00
public stop(): void {
if (!this.handle) {
return;
}
2021-12-10 23:20:24 +00:00
log.info('Stop idle detector');
this.clearScheduledCallbacks();
}
2021-12-10 23:20:24 +00:00
private clearScheduledCallbacks() {
if (this.handle) {
cancelIdleCallback(this.handle);
2021-12-10 23:20:24 +00:00
delete this.handle;
2018-03-21 19:17:32 +00:00
}
clearTimeoutIfNecessary(this.timeoutId);
delete this.timeoutId;
}
2021-12-10 23:20:24 +00:00
private scheduleNextCallback() {
this.clearScheduledCallbacks();
2018-04-27 21:25:04 +00:00
this.handle = window.requestIdleCallback(deadline => {
const { didTimeout } = deadline;
const timeRemaining = deadline.timeRemaining();
const isIdle = timeRemaining >= IDLE_THRESHOLD_MS;
2018-04-27 21:25:04 +00:00
this.timeoutId = setTimeout(
2021-12-10 23:20:24 +00:00
() => this.scheduleNextCallback(),
2018-04-27 21:25:04 +00:00
POLL_INTERVAL_MS
);
if (isIdle || didTimeout) {
this.emit('idle', { timestamp: Date.now(), didTimeout, timeRemaining });
}
});
2018-03-21 19:17:32 +00:00
}
}