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

1

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

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>

Here is my solution:

// You can set binding in your templeteurl with this variable that will display the time couner
// for example <span id='myTimeCounter'>{{expirationCounter}}</span>
expirationCounter: string;
startTimer(secsToStart:number): void {
    var start: number = secsToStart;
    var h: number;
    var m: number;
    var s: number;
    var temp: number;
    var timer: any = setInterval(() =>
    {
        h = Math.floor(start / 60 / 60)
        // remove the hours
        temp = start - h * 60 * 60;
        m = Math.floor(temp / 60);
        // remove the minuets
        temp = temp - m * 60;
        // what left is the seconds
        s = temp;

        // add leading zeros for aesthetics
        var hour = h < 10 ? "0" + h : h;
        var minute = m < 10 ? "0" + m : m;
        var second = s < 10 ? "0" + s : s;

        this.expirationCounter = hour + ":" + minute + ":" + second;

        if (start <= 0) {
            // Time elapsed
            clearInterval(timer);
            this.expirationCounter = "Expired";
            // Make here changes in gui when time elapsed
            //....
        }
        start--;
    }, 1000)
}

using setInterval() function also timmer show in descending order like 10s,9s,8s...

timeLeft: any = 10;
 startTimer() {
    setInterval(() => {
      if (this.timeLeft > 1) {
        this.timeLeft--;
      } else {
        this.timeLeft = 10;
      }
    }, 1000);
  }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Robert Thorne

Robert Thorne

Automotive & Future Transportation Editor

Robert Thorne covers electric vehicle innovations, autonomous driving systems, global mobility trends, and automotive engineering developments.

Share this article
Twitter Facebook Pinterest