【问题标题】:How to start setInterval after object initialization?对象初始化后如何启动 setInterval?
【发布时间】:2021-03-17 16:43:25
【问题描述】:
function Game() {
  this.number = 0;
  const t = setInterval(() => {
      this.number = Math.floor((Math.random() * 10) + 1);
      }, 1000);

  this.checkNumber = () => {
    if (this.number > 5) {
      clearInterval(this.t);
    }
    return this.number > 5;
  }
}


const game = new Game();
console.log(game.number);

我确实有这样的事情,我想更改我的号码,但是 setInterval 在我的对象初始化后似乎没有被初始化。我怎么能不做额外的方法呢?

【问题讨论】:

  • 在您的代码示例中,console.log(game.number) 将在间隔触发更新数字的代码之前执行。也可以尝试间隔运行 console.log。

标签: javascript arrays class object constructor


【解决方案1】:

试试这样的..

class Game () {
  constructor(){
   //call set interval function here
 }

  //put methods here

}

或者自调用函数

(function () {
  // body
})();

查看更多@https://blog.mgechev.com/2012/08/29/self-invoking-functions-in-javascript-or-immediately-invoked-function-expression/

箭头语法

(() => {
  //body
})()

箭头语法+参数

((n) => {
  //body
})()

【讨论】:

  • 我需要通过函数构造函数来做到这一点 :( (school)+
  • @Shakered 尝试自执行函数
  • @Shakered 是的,它可以
  • 谢谢,但是我的变量 this.number 在这个对象初始化后是未定义的,你知道我可以做些什么来改变它吗?
  • 好的,我明白了。我做了这样的事情
【解决方案2】:
function Game() {
  (() => {
    this.t = setInterval (() => {
      this.number = Math.floor ((Math.random () * 10) + 1);
      console.log(this.number);
      this.checkNumber();
    }, 1000);
  })();

  this.checkNumber = () => {
    if (this.number > 5) {
      clearInterval(this.t);
    }
    return this.number > 5;
  };
}


const game = new Game();

做了这样的事情,它可以工作,谢谢上面

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-05
    相关资源
    最近更新 更多