signal-desktop/ts/IdleDetector.ts

55 lines
1.4 KiB
TypeScript
Raw Normal View History

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