使用 TypeScript 中的类字段运行和停止计时器

问题描述 投票:0回答:1

我想创建包含带有计时器的字段的类。主要问题是 我无法将计时器默认值设置为未定义或 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();
node.js typescript class setinterval clearinterval
1个回答
3
投票

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;
    }
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.