gpt4 book ai didi

javascript - 在 while 循环中更新了一个 div

转载 作者:行者123 更新时间:2023-11-29 20:48:14 26 4
gpt4 key购买 nike

我有这样一个类

class Person {
constructor(name, age) {
this.name = name;
this.age = age;
this.oldEnough = 30;
}

celebrate(div) {
let currentAge = 0;

while(!this.isOldEnough(currentAge)) {
const timer = setInterval(() => {
currentAge = currentAge + 1;
div.innerHTML = `age is ${count} years old`;
}, 100);
}

div.innerHTML = `Happy birthday ${this.name}!`;


//clearInterval(timer);
}

isOldEnough(age) {
return age === this.oldEnough;
}
}

const jc = new Person('John', 0);
jc.celebrate(document.querySelector('#greeting'));

当然,divwhile 循环时不会更新,这就是我在这里的原因。我做错了什么?

最佳答案

如果你想使用 while 循环,你可以在 try...finally block 中使用生成器,并使用 setInterval 调用迭代器/p>

class Person {
constructor(name, age) {
this.name = name;
this.age = age;
this.oldEnough = 30;
}

celebrate(div) {
let self = this;

function* count() {
try {
while (!self.isOldEnough()) {
yield div.innerHTML = `age is ${self.age++} years old`;
}
} finally {
div.innerHTML = `Happy birthday ${self.name}!`;
clearInterval(timer);
}
}

let it = count();
let timer = setInterval(() => it.next(), 100)
}

isOldEnough() {
return this.age === this.oldEnough;
}
}

const jc = new Person('John', 0);
jc.celebrate(document.querySelector('#greeting'));
<div id="greeting"></div>

关于javascript - 在 while 循环中更新了一个 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53345003/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com