1.新建一个js或ts文件
export function getPublicTimer() {
const timers:any = {};
const start = (key, intervalFunction,val) => {
if (timers[key]) {
clearInterval(timers[key]); // 如果已经存在,则清除旧的定时器
}
timers[key] = setInterval(intervalFunction, val); // 5分钟 5 * 60 *
};
const stop = (key) => {
if (timers[key]) {
clearInterval(timers[key]);
delete timers[key]; // 删除定时器
}
};
const stopAll = () => {
for (const key in timers) {
clearInterval(timers[key]);
delete timers[key]; // 清除所有定时器
}
};
return { start, stop, stopAll };
}
2.引入 并且使用
import { getPublicTimer } from "@/utils/PublicTimer";
const { start, stop, stopAll } = getPublicTimer();
onMounted(() => {
start('keliu2',todayint,5 * 60 *1000);
});
//如果需要重置函数中的变量
//重置定时器 切换tab
const resetTimer = () => {
stop('keliu1'); // 停止当前定时器
start('keliu1', () => {
exiting(true); // 可以传递参数 在函数中判断修改
times.value = getCurrentFormattedDate2(); //也可以直接修改
}, 5 * 60 *1000); // 重新启动定时器
};
3.移除定时器 释放资源
stopAll(); // 停止所有定时器
stop('timer1'); //停止单独的定时器