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();