如何重启间隔?

时间:2019-01-22 11:50:03

标签: javascript angular

我需要重新启动一个间隔,即当用户单击按钮时开始一个新的1秒间隔。

home.html

<ion-header>
  <ion-navbar>
    <ion-title>
      TimerDemo
    </ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding>

  <h1>{{ time_elapsed }}</h1>
  <button ion-button (click)="restart()">restart</button>

</ion-content>

home.ts

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  timestamp = new Date().getTime();
  timer: any;
  time_elapsed: string;


  constructor(public navCtrl: NavController) {}  

  ionViewDidLoad() {
    this.timer = setInterval(this.function, 1000);
  }

  function = () => {
    let now = new Date().getTime();
    let difference = now - this.timestamp;

    let days = Math.floor(difference / (1000 * 60 * 60 * 24));
    let hours = Math.floor((difference % (1000 * 60 * 60 * 24)) / (1000 * 60 * 24));
    let minutes = Math.floor((difference % (1000 * 60 * 60)) / (1000 * 60));
    let seconds = Math.floor((difference % (1000 * 60)) / 1000);

    this.time_elapsed = `${days} d ${hours} h ${minutes} m ${seconds} s`;
  }

  restart() {
    clearInterval(this.timer);
    this.timer = setInterval(this.function, 1000);
  }

}

我希望当用户单击按钮并触发time_elapsed方法时能够重新启动计时器restart()。实际结果是计时器没有重新启动。

1 个答案:

答案 0 :(得分:2)

尝试一下

R CMD build <package name>