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 };
|
}
|