封装定时器
1、要停止某个特定的定时器,你可以修改TimerManager类,为每个定时器分配一个唯一标识符(ID),并提供一个方法来停止具有特定ID的定时器。这样,你就可以精确控制要停止的定时器。下面是如何实现这个功能的示例代码:
function TimerManager() {
this.timers = {}; // 使用对象来存储定时器,便于通过ID访问
this.nextId = 0; // 用于生成唯一ID
// 添加定时器并返回其ID
this.addTimer = function(callback, interval) {
const id = this.nextId++;
let timer = null;
const repeat = () => {
callback();
timer = setTimeout(repeat, interval);
};
repeat(); // 启动定时器
// 保存定时器
this.timers[id] = {
stop: function() {
clearTimeout(timer);
}
};
return id; // 返回定时器的ID
};
// 停止指定ID的定时器
this.stopTimer = function(id) {
if (this.timers[id]) {
this.timers[id].stop();
delete this.timers[id]; // 从存储中移除
}
};
// 停止所有定时器
this.stopAll = function() {
Object.values(this.timers).forEach(timer => timer.stop());
this.timers = {}; // 清空定时器对象
};
}
// 使用示例
const timerManager = new TimerManager();
// 添加定时器,保存ID
const timerId1 = timerManager.addTimer(() => {
console.log('定时器1');
}, 1000);
const timerId2 = timerManager.addTimer(() => {
console.log('定时器2');
}, 2000);
// 假设你想停止定时器1
// setTimeout(() => {
// timerManager.stopTimer(timerId1);
// console.log('定时器1已停止');
// }, 5000);
// 如果想停止所有定时器
// setTimeout(() => {
// timerManager.stopAll();
// console.log('所有定时器已停止');
// }, 10000);
在这个版本的TimerManager中,每当添加一个新的定时器时,都会生成一个唯一的ID,并将定时器存储在一个对象中,这使得你可以通过ID来引用和控制每个定时器。stopTimer方法允许你通过提供定时器的ID来停止特定的定时器,而stopAll方法可以用来停止所有定时器。
这样的设计使得管理和控制单个或多个定时器变得更加灵活和方便。
浙公网安备 33010602011771号