运行setimeout延迟时间

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

我想在运行时更改或更新setimeout延迟时间。我已经通过使用debounceTime()作为替代进行了验证。但是需要找到如何更新已经提到的延迟时间。

在上面的代码片段中,我提到的延迟为10秒。但是我需要的是在触发鼠标事件时启动此settimeout之后,我需要在settimeout运行时更新延迟时间。

请告知。谢谢

javascript angular typescript rxjs6
1个回答
0
投票

您可以创建Timer class来提供帮助。请参见下面的implementationTimer.start启动计时器。如果要更改某些数据和re-run。然后使用Timer.interrupt。这将占用增量并再次运行该函数。您可以修改逻辑。

class Timer {
  constructor(cb, ms = 2000) {
    this._ms = ms;
    this.ms = ms;
    this.cb = cb;
    this.timer = null;
    this.startedAt = null;
  }
  start() {
    this.startedAt = new Date().getTime();
    clearTimeout(this.timer);
    console.log("started");
    this.timer = setTimeout(() => {
      this.cb();
    }, this._ms);
  }
  intrupt() {
    const timeSpends = new Date().getTime() - this.startedAt;
    const timeLeft = this.ms - timeSpends;
    if (timeLeft > 0) {
      this._ms = timeLeft;
      this.start();
    }
  }
}
console.time("TIME");
let counter = 0;
const timer = new Timer(() => {
  console.timeEnd("TIME");
  console.log("counter: ", counter);
});

timer.start();
setTimeout(function cancel() {
  counter++;
  timer.intrupt();
}, 1000);
© www.soinside.com 2019 - 2024. All rights reserved.