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
import { ref, computed } from 'vue';
 
/**
 * 秒表计时器
 */
export function useTimer() {
  let interval;
  const count = ref(0);
  const running = ref(false);
  const time = computed(() => {
    const hour = Math.floor(count.value / 3600);
    const min = Math.floor((count.value - hour * 3600) / 60);
    const sec = Math.floor(count.value - hour * 3600 - min * 60);
 
    return `${hour.toString().padStart(2, '0')}:${min.toString().padStart(2, '0')}:${sec
      .toString()
      .padStart(2, '0')}`;
  });
 
  function startTimer() {
    if (!running.value) {
      interval = setInterval(() => {
        count.value++;
      }, 1000);
      running.value = true 
    }
  }
 
  function pauseTimer() {
    if (interval) {
      clearInterval(interval);
    }
    running.value = false
  }
 
  function stopTimer() {
    pauseTimer();
    count.value = 0;
  }
 
  return { time, startTimer, pauseTimer, stopTimer, running, count };
}