简单倒数计时器打字稿

时间:2018-07-31 16:56:01

标签: typescript settimeout countdown

我的构造函数中包含以下代码:

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

我真正想要的是显示一个倒计时90秒的数字。现在它立即从90计数到0

2 个答案:

答案 0 :(得分:2)

您可以改用setInterval使函数每1秒调用一次,直到计数器达到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)
    }
}

或者,如果您想要看起来像for并使用setTimeout的东西,则可以使用async/await和Promisses(在这个简单的示例中,这可能会过大):

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

答案 1 :(得分:1)

我发现的另一种解决方案:

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

在您的html中:

<span>{{counter.min}} : {{counter.sec}}</span>