interval-execute
Version:
按照一定时间间隔轮询执行某函数
53 lines (52 loc) • 1.12 kB
JavaScript
/**
* @Author: ZJoker
* @Date: 2023-12-28 16:13:30
* @LastEditTime: 2024-03-22 11:42:44
* @LastEditors: ZJoker
* @Description: 按照一定时间间隔轮询执行某函数
* @FilePath: \IntervalExecute\index.js
* @生活百般滋味,人生需要笑对
*/
class IntervalExecute {
#cleared
#paused
#timer
#fn
#ms
#loading
constructor(fn, ms = 2000) {
this.#cleared = false
this.#paused = false
this.#loading = false
this.#timer = null
this.#fn = fn
this.#ms = ms
this.#execute()
}
clearTimer() {
this.#cleared = true
this.#timer && clearTimeout(this.#timer)
this.#timer = null
}
pause() {
this.#paused = true
}
async restart() {
this.clearTimer()
this.#cleared = false
this.#paused = false
await this.#execute()
}
async #execute() {
if (this.#cleared) return
if (this.#paused) return
if(this.#loading) return
this.#loading = true
await this.#fn()
this.#loading = false
this.#timer = setTimeout(async () => {
await this.#execute()
}, this.#ms)
}
}
export default IntervalExecute