1. 首页
  2. 游戏开发
  3. 其他
  4. JavaScript定时器封装解决叠加和清除问题

JavaScript定时器封装解决叠加和清除问题

上传者: 2023-03-09 07:29:37上传 RAR文件 994B 热度 5次
// 封装一个定时器工具类
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();
下载地址
用户评论