Angular Timer 来计算时间

标签 angular typescript

我正在尝试创建一个计时器来从 0 开始计算时间。

但是,当我单击按钮时,时间不计算在内,有谁知道为什么?

如何以这种格式获取此计时器 {{hours}}: {{mminutes}}: {{sseconds}}?

谢谢!

我的代码

Stackblitz

组件.ts

time: number = 0;
interval;

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

pauseTimer() {
    clearInterval(this.interval);
}

最佳答案

你喜欢这个日期:'mm:ss' 在 html 中

组件

 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> 

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

{HH:MM:SS} 格式
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;
    }

关于Angular Timer 来计算时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58914756/

相关文章:

typescript - 用于right = | _a |的Rust泛型类型实现| b | b

json - Angular:HttpClient 错误,响应为空 200/201(总是调用 JSON.parse (""))

typescript - Ionic2/Angular2/ typescript : How to access a DOM element in a function 2016

javascript - 查找函数对象的替代方案有哪些?

javascript - 使用 NodeJS 从 package.json 获取名称属性

TypeScript 参数类型推断失败

node.js - 通过 Webpack(终端)执行 Typescript Jasmine 测试以测试 Angular2

Angular - 与 react 形式的子组件交互

angular - Angular 中的 StaticInjector 与 ReflectiveInjector

unit-testing - 使用原生 View 封装时访问嵌套组件的DebugElement