Files
qingdao-employment-service/utils/GlobalInactivityManager.js

76 lines
2.2 KiB
JavaScript
Raw Normal View History

2025-12-17 18:27:59 +08:00
// utils/GlobalInactivityManager.js
export class GlobalInactivityManager {
constructor(callback, timeout = 60000) {
this.callback = callback
this.timeout = timeout
this.timer = null
this.isPaused = false
this.lastActivityTime = 0
this.THROTTLE_DELAY = 300
this.lowFreqEvents = ['mousedown', 'click', 'keydown', 'touchstart']
this.highFreqEvents = ['mousemove', 'scroll', 'wheel', 'pointermove']
}
resetTimer = () => {
if (this.isPaused) return
if (this.timer) clearTimeout(this.timer)
this.timer = setTimeout(() => {
this.callback()
this.pause()
}, this.timeout)
}
handleUserActivity = () => {
const now = Date.now()
if (now - this.lastActivityTime > this.THROTTLE_DELAY) {
this.lastActivityTime = now
this.resetTimer()
}
}
handleVisibilityChange = () => {
if (document.hidden) {
this.pause()
} else {
this.resume()
}
}
start() {
if (this.isPaused) return
this.resetTimer()
this.lowFreqEvents.forEach(event => {
document.addEventListener(event, this.resetTimer, true)
})
this.highFreqEvents.forEach(event => {
document.addEventListener(event, this.handleUserActivity, true)
})
document.addEventListener('visibilitychange', this.handleVisibilityChange)
}
pause() {
this.isPaused = true
if (this.timer) clearTimeout(this.timer)
this.lowFreqEvents.forEach(event => {
document.removeEventListener(event, this.resetTimer, true)
})
this.highFreqEvents.forEach(event => {
document.removeEventListener(event, this.handleUserActivity, true)
})
document.removeEventListener('visibilitychange', this.handleVisibilityChange)
}
resume() {
this.isPaused = false
this.start() // 现在 this 指向正确,事件能正常绑定和触发
}
destroy() {
this.pause()
this.callback = null
}
}