node.js setInterval不会触发此操作。宾语

时间:2018-08-03 06:53:33

标签: node.js time setinterval

当页面加载后,该功能的控制台日志部分会向我显示当前秒数+ 3,但不会重复,并且(innerText = ....)完全不起作用。我仅将控制台日志部分添加到代码中以尝试进行故障排除,内部文本更改是重要的部分。

class Main {
  constructor() {
    // Initiate variables
    this.TimerTexts = [];
    this.infoTexts = [];
    this.training = -1; // -1 when no class is being trained
    this.videoPlaying = false;

    this.currentTime2 = new Date(Date.now());
    this.currentTime = new Date(Date.now());
    this.remTime = this.currentTime.getSeconds() + 3;
    this.looper = window.setInterval(this.intervalfunc(), 1000);
  }

  // ...

  intervalfunc() {
    this.TimerTexts.innerText = `Time: ${this.remTime} `;
    console.log(this.remTime);
  }

  // ...
}

2 个答案:

答案 0 :(得分:0)

问题在于您正在调用 intervalfunc,而不是作为setInterval的函数传入。

此外,您需要将该函数绑定到您的实例。

this.looper = window.setInterval(this.intervalfunc.bind(this), 1000);

答案 1 :(得分:0)

您可以使用箭头功能,在箭头功能内部可以调用intervalfunc。

class Main {
  constructor() {
    // Initiate variables
    this.TimerTexts = [];
    this.infoTexts = [];
    this.training = -1; // -1 when no class is being trained
    this.videoPlaying = false;

    this.currentTime2 = new Date(Date.now());
    this.currentTime = new Date(Date.now());
    this.remTime = this.currentTime.getSeconds() + 3;
    this.looper = window.setInterval(()=>this.intervalfunc(), 1000);
  }

  intervalfunc() {
    this.TimerTexts.innerText = `Time: ${this.remTime} `;
    console.log(this.remTime);
    this.remTime += 3;
  }
}

new Main()

或者您可以

class Main {
  constructor() {
    // Initiate variables
    this.TimerTexts = [];
    this.infoTexts = [];
    this.training = -1; // -1 when no class is being trained
    this.videoPlaying = false;

    this.currentTime2 = new Date(Date.now());
    this.currentTime = new Date(Date.now());
    this.remTime = this.currentTime.getSeconds() + 3;
    var self = this;
    this.looper = window.setInterval(this.intervalfunc.bind(self), 1000);
  }

  intervalfunc() {
    this.TimerTexts.innerText = `Time: ${this.remTime} `;
    console.log(this.remTime);
    this.remTime += 3;
  }
}

new Main()