我的构造函数中包含以下代码:
constructor(){
for (let i = 0; i < 90; i++) {
setTimeout(() => {
this.counter = this.counter - 1;
}, 1000)
}
}
我真正想要的是显示一个倒计时90秒的数字。现在它立即从90计数到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)
}
}
或者,如果您想要看起来像
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);
}
}
}
关于typescript - 简单倒数计时器 typescript ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51618496/