SEC_Warehouse/hooks/useCountdown.js

50 lines
813 B
JavaScript

/**
* 创建一个简单倒计时控制器,适配 Vue2 Options API。
* @param {object} options
* @param {number} options.duration 倒计时总秒数
* @param {(value:number)=>void} options.onChange 每次变化回调
*/
export function createCountdown(options = {}) {
const {
duration = 60,
onChange = () => {}
} = options
let timer = null
let current = 0
function emit() {
onChange(current)
}
function clear() {
if (timer) {
clearInterval(timer)
timer = null
}
}
function start() {
clear()
current = duration
emit()
timer = setInterval(() => {
current -= 1
if (current <= 0) {
current = 0
emit()
clear()
return
}
emit()
}, 1000)
}
return {
start,
clear
}
}