更新了while循环内的div

时间:2018-11-16 20:33:44

标签: javascript

我有一个像这样的班

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'));

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

3 个答案:

答案 0 :(得分:2)

如果要使用while循环,可以在try...finally块内使用generator并使用setInterval调用迭代器

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>

答案 1 :(得分:0)

不需要使用while循环,仅使用间隔就可以实现

celebrate(div) {
  let currentAge = 0;


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


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


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

答案 2 :(得分:0)

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

    celebrate(div) {   
            const timer = setInterval(() => {
                if(!this.isOldEnough(this.age)){
                    this.age++;
                    console.log(this.name + ' is ' + this.age + ' years old ')
                }
                else{
                    clearInterval(timer);
                }
            }, 100);

        console.log('Happy birthday ' + this.name)
    }

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

我认为这就是你所追求的。您的构造函数无法正常运行,因为proper syntaxconstructor(...),您应该尝试利用.setInterval() takes a function as its first parameter.这一事实,如果您有其他条件必须更改根据该人是否“足够大”,您可以将其放入if语句的{}中。

无论如何,希望这会有所帮助。