运行时更改setimeout延迟时间



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

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

请告知。感谢

您可以创建一个Timer class来提供帮助。请参阅下面的implementationTimer.start启动定时器。如果您想更改一些数据和CCD_ 4。然后使用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);

最新更新