dytyqx
13 小时以前 438057e8e7bd7ea3d8d2cfc34eee04e6ea24f6f8
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
class TimerManager {
  constructor() {
    this.timers = new Map(); // 存储定时器:key=自定义标识,value={id, type, callback, interval, isPaused: false}
  }
 
  /**
   * 创建定时器
   * @param {String} key 定时器唯一标识(如:'countdown')
   * @param {Function} callback 执行的业务函数
   * @param {Number} interval 执行间隔(ms)
   * @param {String} type 类型:interval(重复)/ timeout(单次)
   * @returns {void}
   */
  createTimer(key, callback, interval = 1000, type = 'interval') {
    // 先清除同名定时器,避免重复创建
    this.clearTimer(key);
 
    let timerId = null;
    const timerConfig = {
      id: null,
      type,
      callback,
      interval,
      isPaused: false
    };
 
    if (type === 'interval') {
      timerId = setInterval(() => {
        // 暂停状态不执行
        if (!timerConfig.isPaused) {
          callback();
        }
      }, interval);
    } else if (type === 'timeout') {
      timerId = setTimeout(() => {
        if (!timerConfig.isPaused) {
          callback();
          this.clearTimer(key); // 单次执行后自动清除
        }
      }, interval);
    }
 
    timerConfig.id = timerId;
    this.timers.set(key, timerConfig);
  }
 
  /**
   * 暂停定时器
   * @param {String} key 定时器标识
   */
  pauseTimer(key) {
    const timer = this.timers.get(key);
    if (timer) {
      timer.isPaused = true;
    }
  }
 
  /**
   * 恢复定时器
   * @param {String} key 定时器标识
   */
  resumeTimer(key) {
    const timer = this.timers.get(key);
    if (timer) {
      timer.isPaused = false;
    }
  }
 
  /**
   * 清除单个定时器
   * @param {String} key 定时器标识
   */
  clearTimer(key) {
    const timer = this.timers.get(key);
    if (timer) {
      if (timer.type === 'interval') {
        clearInterval(timer.id);
      } else if (timer.type === 'timeout') {
        clearTimeout(timer.id);
      }
      this.timers.delete(key);
    }
  }
 
  /**
   * 清除所有定时器(页面销毁时调用)
   */
  clearAllTimers() {
    this.timers.forEach((timer) => {
      if (timer.type === 'interval') {
        clearInterval(timer.id);
      } else if (timer.type === 'timeout') {
        clearTimeout(timer.id);
      }
    });
    this.timers.clear();
  }
}
 
// 导出单例
export default new TimerManager();