riku
2024-01-10 54b5fa2047324b81b6d2ee7f830693267f946c0a
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
87
88
89
90
91
92
93
94
95
import { ref, computed, watch } from 'vue';
import { useNow } from '@vueuse/core';
 
/**
 * 秒表计时器
 */
export function useTimer() {
  const startTime = ref(new Date());
  const endTime = ref(new Date());
  const { now, pause, resume } = useNow({ controls: true });
 
  // 时间偏移量(当初始时间从服务器等外部设备获取时,浏览器所在设备的时间会与其有误差,为了计时器严格在0秒启动,记录其之间的偏移量)
  const offset = ref(0)
  // 运行状态,0:停止;1:运行中;2:暂停
  const status = ref(0);
  const time = computed(() => {
    if (status.value == 0) {
      return `00:00:00`;
    }
 
    let seconds = 0;
    if (status.value == 2) {
      seconds = endTime.value.getTime() - startTime.value.getTime();
    } else {
      seconds = now.value.getTime() - startTime.value.getTime();
    }
    seconds = (seconds + offset.value) / 1000
    const hour = Math.floor(seconds / 3600);
    const min = Math.floor((seconds - hour * 3600) / 60);
    const sec = Math.floor(seconds - hour * 3600 - min * 60);
 
    // console.log(seconds);
    // console.log(hour);
    // console.log(min);
    // console.log(sec);
 
    return `${hour.toString().padStart(2, '0')}:${min.toString().padStart(2, '0')}:${sec
      .toString()
      .padStart(2, '0')}`;
  });
 
  watch(startTime, (nV)=>{
    
  })
 
  /**
   * 启动计时器
   * @param {Date} s 初始时间
   */
  function startTimer(s) {
    status.value = 1;
    if (s) {
      startTime.value = new Date(s);
    } else {
      startTime.value = new Date();
    }
    resumeTimer();
  }
 
  /**
   * 继续计时器
   */
  function resumeTimer() {
    // now.value = startTime.value;
    offset.value = startTime.value.getTime() - now.value.getTime()
    resume();
  }
 
  /**
   * 暂停计时器
   */
  function pauseTimer(s, e) {
    status.value = 2;
    if (s) {
      startTime.value = new Date(s);
    }
    if (e) {
      endTime.value = new Date(e);
    } else {
      endTime.value = new Date();
    }
    offset.value = 0
    pause();
  }
 
  /**
   * 停止计时器
   */
  function stopTimer() {
    pauseTimer();
    status.value = 0;
  }
 
  return { time, startTimer, resumeTimer, pauseTimer, stopTimer, status, startTime };
}