Search code examples
javascriptangulartypescripttimercounter

Angular countup from timer from a start number of seconds


How can I do a countup timer in Angular from a certain start number of seconds? Also if it's possible I need the format to be hh:mm:ss.

I have tried to do something like this, getAlarmDuration being called from the template with a duration in seconds.

getAlarmDuration(duration: number): any {
    this.countStart = duration;
    setInterval(this.setTime, 1000);
  }

  setTime(): void {
    ++this.countStart;
    console.log(this.pad(parseInt((this.countStart / 60).toString(), 10)) + ':' + this.pad(this.countStart % 60))
  }

  pad(val: any): string {
    var valString = val + "";
    if (valString.length < 2) {
      return "0" + valString;
    }
    else {
      return valString;
    }
  }

Thanks in advance.


Solution

  • You can use interval from 'rxjs' and map the counter to the desired result.

    import { Component } from '@angular/core';
    import { interval } from 'rxjs';
    import { map } from 'rxjs/operators';
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css']
    })
    export class AppComponent {
      name = 'Count';
      currentSeconds = 60;
    
      // interval will emit every 1000ms
      count$ = interval(1000).pipe(
        // transform the stream to the result you want -- hh:mm:ss 
        map(count => this.format(count + this.currentSeconds * 1000))
      );
    
      format(seconds: number): string {
        return new Date(seconds + +new Date()).toLocaleString('en-EN', {
          hour: '2-digit',
          minute: '2-digit',
          second: '2-digit'
        });
      }
    }
    

    Here is a link to stackblitz sample working example of this