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();
Define the
timerasNodeJS.Timer | nulland init it withnull. Check that the timer is initialized when callingstop, and also assignnullto timer after clearing it: