I would like to create the class containing a field with timer. The main problem is that
I can’t set the timer default value undefined or null, because TypeScript doesn’t allow this.
I need to create an empty timer and run or stop it with relevant class methods. Now this script doesn’t even run necessary timer with entered interval when I call start method.
class Test {
timer: NodeJS.Timer = setInterval(() => {console.log('1')}, 1000);
start(interval: number) {
this.timer = setInterval(() => console.log('Timer is working!'), interval);
}
stop() {
clearInterval(this.timer);
}
}
const test = new Test();
test.start(5000);
test.stop();
>Solution :
Define the timer as NodeJS.Timer | null and init it with null. Check that the timer is initialized when calling stop, and also assign null to timer after clearing it:
class Test {
timer: NodeJS.Timer | null = null;
start(interval: number) {
this.timer = setInterval(() => console.log('Timer is working!'), interval);
}
stop() {
if(this.timer) {
clearInterval(this.timer);
this.timer = null;
}
}
}