usha
usha

Reputation: 23

Changing setimeout delay time while its running

I would like to change Or update the setimeout delay time while it's running. I have verified by using debounceTime() as an alternate. But need to find how to update the ulready mentioned delay time.instead of creating new.

In the above code snippet I have mentioned the delay as 10 sec. But my need is after this settimeout is started when a mouseevent is triggered I need to update the delay time while settimeout is running.

Kindly advise. Thanks

Upvotes: 1

Views: 61

Answers (1)

xdeepakv
xdeepakv

Reputation: 8135

You can create a Timer class to help. Please see the below implementation. Timer.start to start the timer. if you want to change some data and re-run. Then use Timer.interrupt. It will take delta and run the function again. You can modify your logic.

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

Upvotes: 1

Related Questions