JavaScript定时器封装解决叠加和清除问题
// 封装一个定时器工具类
class Timer {
constructor() {
this.timer = null;
}
// 开始计时
start(callback, interval) {
this.stop();
this.timer = setInterval(callback, interval);
}
// 停止计时
stop() {
clearInterval(this.timer);
this.timer = null;
}
}
// 使用示例
const timer = new Timer();
timer.start(() => {
console.log('Hello, world!');
}, 1000);
timer.stop();
下载地址
用户评论