我想创建包含带有计时器的字段的类。主要问题是 我无法将计时器默认值设置为未定义或 null,因为 TypeScript 不允许这样做。 我需要创建一个空计时器并使用相关的类方法运行或停止它。现在,当我调用 start 方法时,该脚本甚至不会运行输入间隔的必要计时器。
class Test {
timer: NodeJS.Timer = setInterval(() => { console.log('1') }, 1000);
start(interval: number) {
this.timer = setInterval(() => console.log('Timer is working!'), interval);
}
stop() { clearInterval(this.timer); }
}
const test = new Test();
test.start(5000);
test.stop();
将
timer
定义为 NodeJS.Timer | null
并用 null
初始化它。检查调用stop
时定时器是否已初始化,并在清除定时器后将null
分配给定时器:
class Test {
timer: NodeJS.Timer | null = null;
start(interval: number) {
this.stop();
this.timer = setInterval(() => console.log('Timer is working!'), interval);
}
stop() {
if(this.timer) {
clearInterval(this.timer);
this.timer = null;
}
}
}