Search code examples
javascripttypescriptangular7

How can I view a set timers countdown Angular 7


How can I view my timer's countdown when it's started? I've tried binding it to a variable but it comes up as [object Object]:

setTime(time) {
    if (this.settime >= 5 ) {
      this.currentTime = time;
      this.alerttime = this.settime;
    this.notifiy.showInfo( 'Timer set for ' + this.settime + ' Minutes train is due in ' + time + ' Minutes' , '');
    const val = this.settime * 60000;
    const source = timer(val);
    this.time = source;
    console.log(this.time); // this prints out the observbale function Ive also tryed to bind it in the subscribe method but no joy.
    const subscribe = source.subscribe(value => { this.alertTimer(); });
    this.settime = '';
    //cordova.plugins.backgroundMode.enable();
    } else {
      this.notifiy.showFailure('You cant set the timer below 5 minutes', '');
    }
  }

I'm not sure what I am doing wrong.


Solution

  • The short answer is "you cant" as the actual timer you are using does not have this property, as per the documentation.

    But depending on what you want to do with it, you probably want to keep track of the actual elapsed time separately, for this you could use "interval" instead.

    https://rxjs.dev/api/index/function/interval

    Say you set a timer() for 120 seconds, so it executes at the planned end. And then you use a separate interval() of 1s to keep track of elapsed time, and update UI etc, until the main timer has ended.

    Pseudo-code, that shows the concept. From the top of my head, could have typos and such:

    class TimerManager {
    
       private totalSeconds;
       private elapsedSeconds;
    
       private timerSub;
       private intervalSub
    
       // Start the timer
       public startTimer(timerLengthSeconds) {
          this.totalSeconds = timerLengthSeconds;
          var t = new timer(timerLengthSeconds);
          this.timerSub = t.subscribe(t => this.endTimer());
          var i = new interval(1000);
          this.intervalSub = i.subscribe(i => this.intervalElapsed());
       }
    
       // On each interval
       private intervalElapsed() {
          this.elapsedSeconds++;
          var remaining = this.totalSeconds - this.elapsedSeconds;
          console.log(this.elapsedSeconds + "s have elapsed, there are " + remaining + "s left");
       }
    
       // When the main timer ends
       private endTimer() {
         console.log("The time is up!!");
         this.intervalSub.unsubscribe();
       }
    
    }