abc
abc

Reputation: 512

Time Counter - Typescript

I want to count the time when I press a button. And what I did until now, was to display the minutes and seconds when I press the button.

Example Time: 21(min):02 (sec)

I want to see when the minutes and seconds change, but I don't know how to do that.

ts.

  startTime = false;
  minutes: number;
  seconds: number;

  getTime() {
    this.startTime = !this.startTime;
    this.runTime();
    setInterval(this.runTime, 1000);
  }

  runTime() {
    this.todayDate = new Date();
    this.minutes = this.todayDate.getMinutes();
    console.log(this.minutes) /* here I can see in console that it prints minutes and seconds in real 
                                time, but in the UI nothing happens, it appears only the date when I 
                                click the button */ 
    this.seconds = this.todayDate.getSeconds();
  }

.html

<button type="button" class="btn btn-primary" (click)="getTime()">Time</button>
<div *ngIf="startTime">
     Time: {{minutes}} : {{seconds}}
</div>

Could you, please help me with this ?

Upvotes: 0

Views: 655

Answers (1)

Sanjay Lohar
Sanjay Lohar

Reputation: 528

Simply write:

import { interval } from 'rxjs';
import { map } from 'rxjs/operators'

interval(1000).pipe(
  map((x) => { /* your code here */ })
);

In RxJS 6+ there's no Observable.interval function.

Upvotes: 1

Related Questions