typescript 简单的倒数计时器打字稿

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51618496/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:33:29  来源:igfitidea点击:

Simple Countdown Timer Typescript

typescriptsettimeoutcountdown

提问by Nicole W.

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

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

回答by Titian Cernicova-Dragomir

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

您可以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)
    }
}

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

或者,如果你想要的东西,看起来像一个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);
        }
    }
}

回答by Rapha?l Etang-Salé

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:

在你的 html 中:

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