haoxuan
2023-11-01 8c84c7277018b259f5b99f26cbfd14603bc4e4c0
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
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 }