简单倒数计时器打字稿 [英] 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)
}
}
我真正想要的是显示一个倒计时90秒的数字。现在,它立即从90计数到0
What I actually want is to display a number which counts down 90 seconds. Right now it counts down from 90 to 0 immediately
推荐答案
您可以使用 setInterval
而是使函数每隔1秒调用一次,直到计数器达到0:
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)
}
}
或者如果您想要类似的
并使用 setTimeout
您可以使用 async / await
和Promisses(对于这个简单的例子,坦白地说,这可能是过大的了):
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);
}
}
}
这篇关于简单倒数计时器打字稿的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文