Files
local_alert/src/stores/globalTimerStore.ts
2024-11-26 16:09:50 +08:00

60 lines
1.5 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import {ref} from 'vue'
import { defineStore } from 'pinia';
// 定义回调类型
type TimerCallback = () => void;
export const useGlobalTimerStore = defineStore('globalTimer', () => {
const intervalId = ref<number | null>(null); // 定时器 ID
const refreshIntervalMs = ref(300000); // 默认刷新间隔5 分钟)
const registeredCallbacks = ref<TimerCallback[]>([]); // 注册的回调函数列表
// 注册回调
const registerCallback = (callback: TimerCallback) => {
if (typeof callback === 'function' && !registeredCallbacks.value.includes(callback)) {
registeredCallbacks.value.push(callback);
}
};
// 注销回调
const unregisterCallback = (callback: TimerCallback) => {
const index = registeredCallbacks.value.indexOf(callback);
if (index !== -1) {
registeredCallbacks.value.splice(index, 1);
}
};
// 启动定时器
const startTimer = () => {
if (!intervalId.value) {
intervalId.value = window.setInterval(() => {
registeredCallbacks.value.forEach((callback) => callback());
}, refreshIntervalMs.value);
}
};
// 停止定时器
const stopTimer = () => {
if (intervalId.value) {
clearInterval(intervalId.value);
intervalId.value = null;
}
};
// 设置定时器间隔
const setRefreshInterval = (interval: number) => {
refreshIntervalMs.value = interval;
stopTimer();
startTimer();
};
return {
refreshIntervalMs,
registerCallback,
unregisterCallback,
startTimer,
stopTimer,
setRefreshInterval,
};
});