This is for frontend Javascript linked to an HTML file if that's relevant. I tried using IIFE for this problem and a bunch of things broke, so I'd like to avoid trying again if possible. I declared a timer that I want to stop conditionally (i.e. backend sends front end a message to stop or timer ticks for thirty seconds, whichever comes first), but I'm not sure how to do this without globally declaring a timer variable.
Here's some dummy code because the actual thing is around 300 lines:
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.
})
How would I avoid declaring a global timer? Is it really that bad to do so?
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);