aleksejjj
aleksejjj

Reputation: 1565

How to restart interval?

I need to restart an interval i.e. start a new 1 second interval when user clicks a button.

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

}

I am expecting to be able to restart the timer time_elapsed when user clicks the button and fires the restart() method. The actual result was that the timer did not restart.

Upvotes: 3

Views: 997

Answers (1)

Suren Srapyan
Suren Srapyan

Reputation: 68665

Try with this

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

setTimeElapsed() {
  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.setTimeElapsed(), 1000);
}

Upvotes: 1

Related Questions