node.js的setInterval不会触发this.对象



当页面加载控制台日志时,函数的一部分显示当前秒数+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);
}
// ...
}

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

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

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

您可以使用箭头函数,在箭头函数内可以调用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()

最新更新