import { StepTimer } from '@/common/utils/stepTimer'
|
import { computed, onUnmounted, ref } from 'vue'
|
|
interface Options {
|
onEnd?: Function
|
onAbort?: Function
|
}
|
|
/**
|
* 格式化计时
|
* @param time
|
*/
|
function formatTime(time: number) {
|
const minutes = Math.floor(time / 60)
|
const seconds = time % 60
|
const minutesString = minutes.toString().padStart(2, '0') // 在分钟数不足两位时,在前面补0
|
const secondsString = seconds.toString().padStart(2, '0') // 在秒数不足两位时,在前面补0
|
return `${minutesString}:${secondsString}`
|
}
|
|
function useCountDown(seconds: number, options?: Options) {
|
let timer = new StepTimer(seconds * 1000, 1000)
|
|
const remainingSeconds = ref<number>(seconds)
|
|
const formattedTime = computed(() => {
|
return formatTime(remainingSeconds.value)
|
})
|
|
const countdownStatus = ref<'stop' | 'running' | 'pause' | 'complete'>('stop')
|
|
function startCountdown() {
|
countdownStatus.value = 'running'
|
timer
|
.start((round) => {
|
remainingSeconds.value = seconds - round
|
})
|
.then(
|
(data) => {
|
countdownStatus.value = 'complete'
|
options?.onEnd?.(data)
|
},
|
(err) => {
|
countdownStatus.value = 'stop'
|
options?.onAbort?.(err)
|
}
|
)
|
}
|
|
onUnmounted(() => {
|
countdownStatus.value = 'stop'
|
timer.destroy()
|
})
|
|
function pauseCountdown() {
|
countdownStatus.value = 'pause'
|
timer.pause()
|
}
|
function continueCountdown() {
|
countdownStatus.value = 'running'
|
timer.continue()
|
}
|
function stopCountdown() {
|
countdownStatus.value = 'stop'
|
timer.abort()
|
}
|
|
function reset() {
|
timer.destroy()
|
remainingSeconds.value = seconds
|
timer = new StepTimer(seconds * 1000, 1000)
|
}
|
|
return {
|
startCountdown,
|
remainingSeconds,
|
pauseCountdown,
|
continueCountdown,
|
stopCountdown,
|
formattedTime,
|
countdownStatus,
|
reset
|
}
|
}
|
|
export { useCountDown }
|