javascript - 如何在避免全局变量的同时声明定时器?
问题描述
这适用于链接到 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.
})
我将如何避免声明一个全局计时器?这样做真的有那么糟糕吗?
解决方案
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);
推荐阅读
- google-cloud-platform - 有没有一种方法可以通过 API 将新项目添加到现有的 GCP 监控工作区?
- reactjs - 将 webpack 和 babel 添加到我的项目后,Reactjs 单击按钮不起作用
- nginx - 如何使用 nginx 位置映射 api 节点?
- python - Pandas:如何将 CSV 的内容读入单列?
- typescript - 使类型互斥,类型可以共享相同的键
- dialogflow-es - 全球(美国)以外的 Dialogflow ES 区域的培训页面
- ruby-on-rails - Jpicker rails:如何在rails中选择透明选项?
- flutter - 用谷歌地图搜索动画?
- javascript - 导入(.xls,.csv)文件并将文件内容粘贴到angularjs的文本区域中
- python - 无法从我的列表中删除“nan”。请提出解决方案我做错了什么?