公共定时器

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'); //停止单独的定时器
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值