【问题标题】:Changing setimeout delay time while its running在运行时更改 settimeout 延迟时间
【发布时间】:2020-04-06 00:50:00
【问题描述】:

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

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

请多多指教。谢谢

【问题讨论】:

  • 请发布您的尝试minimal reproducible example,并具体说明您遇到的问题。人们会很乐意提供帮助。
  • 我不确定这是否可行,因为他们 setTimout 将在事件循环中注册,所以你必须取消前一个并设置一个新的
  • 添加上述代码 (above code snippet)。

标签: javascript angular typescript rxjs6


【解决方案1】:

您可以创建Timer class 来提供帮助。请参阅下面的implementationTimer.start 启动计时器。如果你想改变一些数据和re-run。然后使用Timer.interrupt。它将需要 delta 并再次运行该功能。你可以修改你的逻辑。

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);

【讨论】:

  • 谢谢@xdeepakv。如果它是一个一个一个调用的消息列表,我可以阻止每条消息淡出。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多