82 lines
1.9 KiB
JavaScript
82 lines
1.9 KiB
JavaScript
/*
|
||
开发环境不开启定时器
|
||
*/
|
||
const isStartTimer = process.env.NODE_ENV !== 'development'
|
||
|
||
/**
|
||
* @function 定时器
|
||
* @param fn { function } 执行过程
|
||
* @param duration { timestamp } 间隔时间
|
||
* @param immediate { boolean } 是否立即执行
|
||
* @returns {{stop(): void, restart: restart}}
|
||
*/
|
||
export default function timer(fn, duration = 5 * 1000, immediate = true) {
|
||
// 执行队列
|
||
let processes = []
|
||
let _args = []
|
||
// 定义定时器
|
||
let timer = null
|
||
let _duration = duration
|
||
// 过程支持list和单一函数
|
||
if (Array.isArray(fn)) {
|
||
processes.push.apply(processes, fn)
|
||
} else {
|
||
processes.push(fn)
|
||
}
|
||
/**
|
||
* @function 过程执行器
|
||
* @param processes { Array<function> | function }
|
||
* @param args { any }
|
||
* @returns {Promise<void>}
|
||
*/
|
||
const exec = async (processes, ...args) => {
|
||
_args = args
|
||
try {
|
||
if (timer) {
|
||
clearTimeout(timer)
|
||
timer = null
|
||
}
|
||
for (let process of processes) {
|
||
if (typeof process === 'function') {
|
||
await process(..._args)
|
||
}
|
||
}
|
||
} catch (e) {
|
||
console.error('TimerError:', e)
|
||
} finally {
|
||
if (!isStartTimer) return false
|
||
timer = setTimeout(() => {
|
||
exec(processes, ..._args)
|
||
}, _duration)
|
||
}
|
||
}
|
||
if (immediate) {
|
||
exec(processes)
|
||
}
|
||
return {
|
||
stop () {
|
||
if (timer) {
|
||
clearTimeout(timer)
|
||
timer = null
|
||
processes = null
|
||
_args = null
|
||
}
|
||
},
|
||
clearParams () {
|
||
_args = []
|
||
},
|
||
/**
|
||
* 定时器重启
|
||
* @param args { { params: Array<any>, duration: number } } 回调的参数
|
||
*/
|
||
restart: function (options = {}) {
|
||
const { params = [], duration } = options
|
||
// 不能用全等,对象中的undefined 与 undefined 不是全等
|
||
if (duration != undefined || duration != null) {
|
||
_duration = duration
|
||
}
|
||
exec(processes, ...(params || []))
|
||
}
|
||
}
|
||
}
|