import dayjs, { Dayjs } from 'dayjs'; import duration from 'dayjs/plugin/duration'; dayjs.extend(duration) /** * 閒置偵測。 */ export class IdleDetection { private idle_timer: Dayjs; private MaxIdle = 60 * 15; // 預設 15 分鐘。 private callback: () => void; /** * 初始化。 * @param maxSecond 閒置多久會呼叫 callback。 */ public init(maxSecond?: number) { if(maxSecond !== undefined) { this.MaxIdle = maxSecond; } this.idle_timer = dayjs(); } /** 重置時間,回傳 false 代表有呼叫 callback。 */ public reset() { if(this.idle_timer === undefined) { this.idle_timer = dayjs(); } const now = dayjs(); const diff = dayjs.duration(Math.abs(this.idle_timer.diff(now))); console.log(diff.asSeconds()); if(diff.asSeconds() > this.MaxIdle) { try { this.callback(); } catch(e) { return false; } } this.idle_timer = dayjs(); return false; } /** * 註冊時間超過之後呼叫的 function,只允許一個,後面註冊會蓋掉前面的。 */ public timeoutCallback(cb: () => void) { this.callback = cb; } } const idle = new IdleDetection(); export default idle; // 範例程式: // idle.init(2); // 初始化,可以指定閒置秒數。 // idle.reset(); // 重置時間。 // idle.timeoutCallback(() => { // console.log('reload'); // }); // setTimeout(() => { // idle.reset(); // }, 3000);