Angular 2+计时器功能在其中一个组件中不起作用

时间:2017-12-05 21:10:36

标签: javascript angular typescript

这非常非常奇怪。我有一个定时器功能,它适用于我的所有组件,除了1.但我只是不知道为什么,我也没有任何错误或什么。

我错过了什么?我使用的代码如下所示:

HTML

<p>Time in miliseconds: <b id="tick">{{time}}</b></p>

和我的protected.component.ts

timeBegin = new Date();
  starts = null;
  time = '00:00:00.000';

GetUser(): void {
    this.startTime();
    this.dataService.getUser().subscribe(res => {
      if (res !== undefined) {
        this.dataIsReady = true;
        this.imgSrc = 'data:image/png;base64,' + res['image'];
      }
    });
    this.stopTime();
  }

public clockRun() {
const currentTime = new Date();
const timeElapsed = new Date(currentTime.getTime() - this.timeBegin.getTime());
const hour = timeElapsed.getUTCHours();
const min = timeElapsed.getUTCMinutes();
const sec = timeElapsed.getUTCSeconds();
const ms = timeElapsed.getUTCMilliseconds();

this.time =
    (hour > 9 ? hour : '0' + hour) + ':' +
    (min > 9 ? min : '0' + min) + ':' +
    (sec > 9 ? sec : '0' + sec) + '.' +
    (ms > 99 ? ms : ms > 9 ? '0' + ms : '0' + ms);


}

  startTime() {
    this.timeBegin = new Date();

    this.starts = setInterval(this.clockRun.bind(this), 10);
  }

  stopTime() {
    clearInterval(this.starts);
  }

1 个答案:

答案 0 :(得分:1)

我想你可以简化一下。例如:
在HTML中更好地使用DatePipe,如:

{{ interval | date:'HH:mm:ss SSS':'+0000'}}

在组件中:

  timeBegin: Date;
  interval: Date;

  ngOnInit() {
    this.timeBegin = new Date();
    setInterval(this.tick.bind(this), 100);
  }

  tick() {
    let currentTime = new Date();
    this.interval = new Date(currentTime.valueOf() - this.timeBegin.valueOf());
  }

同样在您的示例中,您立即停止时间,因此看不到进度。尝试在订阅块中执行stopTime,例如:

GetUser(): void {
    this.startTime();
    this.dataService.getUser().subscribe(res => {
      if (res !== undefined) {
        this.dataIsReady = true;
        this.imgSrc = 'data:image/png;base64,' + res['image'];
      }
      this.stopTime();
    });
  }