How to auto start to countdown timer in ionic

I’m using Ionic 3 to countdown timer with hour, minute, and second…

This is my code:
timer.ts:

 /* Initialize and setup the time for question */
  ngOnInit() {
    this.initTimer();
  }
  
  initTimer() {
     // Pomodoro is usually for 25 minutes
    if (!this.timeInSeconds) { 
      this.timeInSeconds = 1500; 
    }
  
    this.time = this.timeInSeconds;
    this.runTimer = false;
    this.hasStarted = false;
    this.hasFinished = false;
    this.remainingTime = this.timeInSeconds;
    
    this.displayTime = this.getSecondsAsDigitalClock(this.remainingTime);
  }
  
  startTimer() {
     this.runTimer = true;
    this.hasStarted = true;
    this.timerTick();
  }
  
  pauseTimer() {
    this.runTimer = false;
  }
  
  resumeTimer() {
    this.startTimer();
  }
  
  timerTick() {
    setTimeout(() => {
  
      if (!this.runTimer) { return; }
      this.remainingTime--;
      this.displayTime = this.getSecondsAsDigitalClock(this.remainingTime);
      if (this.remainingTime > 0) {
        this.timerTick();
      }
      else {
        this.hasFinished = true;
      }
    }, 1000);
  }
  
  getSecondsAsDigitalClock(inputSeconds: number) {
    var sec_num = parseInt(inputSeconds.toString(), 10); // don't forget the second param
    var hours = Math.floor(sec_num / 3600);
    var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
    var seconds = sec_num - (hours * 3600) - (minutes * 60);
    var hoursString = '';
    var minutesString = '';
    var secondsString = '';
    hoursString = (hours < 10) ? "0" + hours : hours.toString();
    minutesString = (minutes < 10) ? "0" + minutes : minutes.toString();
    secondsString = (seconds < 10) ? "0" + seconds : seconds.toString();
    return hoursString + ':' + minutesString + ':' + secondsString;
  }

HTML:

  <ion-item>
        <h1 text-center>{{displayTime}}</h1>
  </ion-item>

I don’t want to use button ‘Play’ and ‘Resume’, and I wished when load screen, the timer will auto countdown time…

How to auto start to countdown timer ?

3 Likes
ngOnInit() {
    this.initTimer();
    this. startTimer();
  }
1 Like

first remove buttons and add function instead and then
add your code in the function given below of your .ts page

ionViewDidLoad() {
    console.log('ionViewDidLoad TimerPage');
<!-- your code -->
  }
2 Likes

@uddyvky: Tks, it worked for me :))

1 Like