Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular Timer to count the time

I am trying to create a timer to count the time from 0.

However, when I click the button the time is not counting, does anyone know why?

How can I get this timer in this format {{hours}}: {{mminutes}}: {{sseconds}}?

Thanks!

My code

Stackblitz

Component.ts

time: number = 0;
interval;

startTimer() {
    this.interval = setInterval(() => {
        if(this.time = 0) {
            this.time++;
        } else {
            this.time= 0;
        }
    },1000)
}

pauseTimer() {
    clearInterval(this.interval);
}
like image 899
Harry Avatar asked Jan 01 '23 12:01

Harry


1 Answers

you like this date: 'mm:ss' in html

Component

 import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  time: number = 0;
  display ;
  interval;

 startTimer() {
    console.log("=====>");
    this.interval = setInterval(() => {
      if (this.time === 0) {
        this.time++;
      } else {
        this.time++;
      }
      this.display=this.transform( this.time)
    }, 1000);
  }
  transform(value: number): string {
       const minutes: number = Math.floor(value / 60);
       return minutes + ':' + (value - minutes * 60);
  }
  pauseTimer() {
    clearInterval(this.interval);
  }
}

HTML:

<button (click)='startTimer()'>Start Timer</button>
<button (click)='pauseTimer()'>Pause</button>

<p>{{display }} Seconds</p> 

Edit: 'mm:ss'

transform(value: number): string {
           const minutes: number = Math.floor(value / 60);
           return minutes + ':' + (value - minutes * 60);
      }

{HH:MM:SS} format

transform(value: number): string {
      var sec_num = value; 
    var hours   = Math.floor(sec_num / 3600);
    var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
    var seconds = sec_num - (hours * 3600) - (minutes * 60);

    if (hours   < 10) {hours   = 0;}
    if (minutes < 10) {minutes = 0;}
    if (seconds < 10) {seconds = 0;}
    return hours+':'+minutes+':'+seconds;
    }
like image 186
Avid Programmer Avatar answered Jan 10 '23 10:01

Avid Programmer