首页 > 解决方案 > 如何在避免全局变量的同时声明定时器?

问题描述

这适用于链接到 HTML 文件的前端 Javascript(如果相关)。我尝试使用 IIFE 来解决这个问题,但很多东西都坏了,所以如果可能的话,我想避免再次尝试。我声明了一个我想有条件地停止的计时器(即后端向前端发送一条消息以停止或计时器滴答三十秒,以先到者为准),但我不确定如何在不全局声明计时器变量的情况下执行此操作。

这是一些虚拟代码,因为实际代码大约是 300 行:

const startTimer = ()=>{
  let time = 30
  const timer = setInterval(()=>{
    if(time === 0){
        clearInterval(timer)
     }
   }
  },1000)
}
startTimer()

socket.on('stop-timer', ()=>{
  //I want to clear the timer when this gets emitted.
})

我将如何避免声明一个全局计时器?这样做真的有那么糟糕吗?

标签: javascripttimersocket.io

解决方案


You could create a simple class (I assume you use ES6 by the look of your code) that will expose cancel method to clearInterval like this:

class Timer {
  constructor(time) {
    this.time = time;
    this._interval = null;
  }

  start() {
    this._interval = setInterval(...);
  }

  cancel() {
    clearInterval(this._interval);
    this._interval = null;
  }
}

const timer = new Timer(30);
timer.start();

socket.on('stop-timer', timer.cancel);

推荐阅读