【问题标题】:Angular countup from timer from a start number of seconds从开始秒数开始的计时器角度计数
【发布时间】:2021-10-22 13:57:52
【问题描述】:

如何在 Angular 中从某个开始的秒数开始计时?另外,如果可能的话,我需要格式为 hh:mm:ss。

我试图做这样的事情,从模板调用 getAlarmDuration,持续时间以秒为单位。

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;
    }
  }

提前致谢。

【问题讨论】:

  • 嗨,请在此处发布代码 sn-p,以便大家在查看后帮助您,谢谢
  • @ZubairSaif 完成
  • 嗨@simpllr 谢谢

标签: javascript angular typescript timer counter


【解决方案1】:

您可以使用“rxjs”中的间隔并将计数器映射到所需的结果。

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'
    });
  }
}

这里是 stackblitz sample 工作示例的链接

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多