Search code examples
angularionic-frameworkionic4

How to Override a function in NgOnit by another function?


I have two functions startTimer() Which I am calling in the NgOnit(). I have also another function stopTimer()and I want it to work when the timer reaches('00:00'). I tried placing the this.stoptimer()function inside the NgOnit and the constructor but it overrides the startimer() function. If I put it outside the class I get an error error TS1068: Unexpected token. A constructor, method, accessor, or property was expected. I am thinking I either need to call the stoptimer() differently or I need to put it inside an if statement in the constructor but I do not know how to call the time property time: BehaviorSubject<string> = new BehaviorSubject('01:00');

export class Pagename implements OnInit {
  sub: any;

  time: BehaviorSubject<string> = new BehaviorSubject('01:00');

  timer: number;
  interval;

  state: 'start' | 'stop' = 'stop';

 ngOnInit() {

    this.startTimer(1);
}
 startTimer(duration: number) {
   this.state = 'start';
   clearInterval(this.interval);
   this.timer = duration * 60;
   this.interval = setInterval( () => {
     this.updateTimeValue();
   }, 1000);

 }
 stopTimer() {
   clearInterval(this.interval);
   this.time.next('00:00');
   this.state = 'stop';

 }

 updateTimeValue() {
   let minutes: any = this.timer / 60;
   let seconds: any = this.timer % 60;

   minutes = String('0' + Math.floor(minutes)).slice(-2);
   seconds = String('0' + Math.floor(seconds)).slice(-2);

   const text = minutes + ':' + seconds;
   this.time.next(text);


   --this.timer;
 }
}

Solution

  • updateTimeValue() {
        let minutes: any = this.timer / 60;
        let seconds: any = this.timer % 60;
    
        minutes = String('0' + Math.floor(minutes)).slice(-2);
        seconds = String('0' + Math.floor(seconds)).slice(-2);
    
        const text = minutes + ':' + seconds;
        this.time.next(text);
    
        --this.timer;
        // VVVVVVVVVVVV this is the change
        if (this.timer === 0) {
            this.stopTimer();
        }
    }
    

    Or, for short:

    updateTimeValue() {
        let minutes: any = this.timer / 60;
        let seconds: any = this.timer % 60;
    
        minutes = String('0' + Math.floor(minutes)).slice(-2);
        seconds = String('0' + Math.floor(seconds)).slice(-2);
    
        const text = minutes + ':' + seconds;
        this.time.next(text);
    
        // decrement and check equality in the same line
        if (--this.timer === 0) {
            this.stopTimer();
        }
    }