工具类定时器的暂定和启动

模拟setInterval实现暂停和重启的功能

/** timer.ts */
export default class Timer {
  /** 间隔时间 */
  private interval: number;

  private timeout: NodeJS.Timeout | null;

  /** 定时器的运行状态 */
  public running: boolean;

  /** 回调函数 */
  private callback: () => void;

  constructor(interval: number, callback: () => void) {
    this.interval = interval;
    this.timeout = null;
    this.running = false;
    this.callback = callback;
  }

  // 定时器开始
  public start(): void {
    if (this.running) return;
    this.running = true;
    this.run(); // 直接调用run,而不是setTimeout,run方法中会自己处理setTimeout逻辑
  }

  // 执行定时器
  public run(): void {
    if (!this.running) return;
    console.log('执行任务 ...', this.timeout);
    this.callback();
    if (this.timeout) {
      clearTimeout(this.timeout); // 清除前一个timeout以免重复
    }
    this.timeout = setTimeout(() => this.run(), this.interval);
  }

  // 暂停/停止定时器
  public stop(): void {
    if (this.timeout) {
      clearTimeout(this.timeout);
    }
    console.log('暂停任务 ...', this.timeout);
    this.running = false;
  }

  // 暂停后恢复定时器
  public resume(): void {
    if (this.running || this.timeout === null) return;
    console.log('重启任务 ...');
    this.running = true;
    this.run();
  }
}

功能实现

<template>
  <a-button class="ml-5" @click="startInterval()">
     <template #icon><icon-play-arrow-fill /></template>
       启动
  </a-button>
  <a-button v-if="isPaused" class="ml-5" @click="pauseInterval()">
    <template #icon><icon-pause-circle-fill /></template>
     暂停
  </a-button>
  <a-button v-if="!isPaused" class="ml-5" @click="resumeInterval()">
    <template #icon><icon-refresh /></template>
     重启
  </a-button>
</template>


<script lang="ts" setup>
import { ref } from 'vue';
import Timer from '@/utils/timer';

const isPaused = ref();

const startInterval = () => {
  isPaused.value = true;
  timer.start();
};

// 重启计时器
const resumeInterval = () => {
  isPaused.value = true;
  timer.resume();
};

// 暂定计时器
const pauseInterval = () => {
  isPaused.value = false;
  timer.stop();
};
</script>

实现效果

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值