Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Run and stop timer using class field in TypeScript

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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;
    }
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading