Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple Countdown Timer Typescript

I have the following code in my constructor:

constructor(){
for (let i = 0; i < 90; i++) {
  setTimeout(() => {
    this.counter = this.counter - 1;
  }, 1000)
 }
}

What I actually want is to display a number which counts down 90 seconds. Right now it counts down from 90 to 0 immediately

like image 338
Nicole W. Avatar asked Jul 31 '18 16:07

Nicole W.


2 Answers

You can use setInterval instead to make the function be called every 1 second until the counter reaches 0:

class Timer {
    constructor(public counter = 90) {

        let intervalId = setInterval(() => {
            this.counter = this.counter - 1;
            console.log(this.counter)
            if(this.counter === 0) clearInterval(intervalId)
        }, 1000)
    }
}

Or if you want something that looks like a for and uses setTimeout you could use async/await and Promisses (admittedly this might be overkill for this simple example):

function delay(delay: number) {
    return new Promise(r => {
        setTimeout(r, delay);
    })
}
class Timer {
    constructor(public counter = 90) {
        this.doTimer();
    }
    async doTimer() {
        for (let i = 0; i < this.counter; i++) {
            await delay(1000);
            this.counter = this.counter - 1;
            console.log(this.counter);
        }
    }
}
like image 97
Titian Cernicova-Dragomir Avatar answered Oct 10 '22 09:10

Titian Cernicova-Dragomir


Another solution I found :

counter: { min: number, sec: number }

  startTimer() {
    this.counter = { min: 30, sec: 0 } // choose whatever you want
    let intervalId = setInterval(() => {
      if (this.counter.sec - 1 == -1) {
        this.counter.min -= 1;
        this.counter.sec = 59
      } 
      else this.counter.sec -= 1
      if (this.counter.min === 0 && this.counter.sec == 0) clearInterval(intervalId)
    }, 1000)
  }

And in your html:

<span>{{counter.min}} : {{counter.sec}}</span>
like image 31
Raphaël Etang-Salé Avatar answered Oct 10 '22 08:10

Raphaël Etang-Salé