我的构造函数中有以下代码:
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
和承诺(诚然,对于这个简单的例子来说这可能有点过分了):
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);
}
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)