Home > Software engineering >  How to cancel sleeping using promise?
How to cancel sleeping using promise?

Time:06-21

I'm stuck at problem about sleeping in Javascript. I need a sleep function in ms miliseconds. And I can cancel this sleeping in some place. And in the below is my current solution (it's still bug).

 class Delayer {
   timeoutId = null
   cancelDelay(){
      if(this.timeoutId){
        clearTimeout(this.timeoutId)
      }
   }
   delay(ms){
     return new Promise(resolve => {this.timeoutId = setTimeout(resolve,ms)})
   }
}

const delayer = new Delayer()
await delayer.delay(3000)

But, it's not working like I expect. Because, when I call delayer.cancelDelay() (in some where) then it clear timeout and my delay promise is not resolved.

I don't know as if my mindset is exact. Someone can help me with it. Thanks a lot.

CodePudding user response:

Save the resolve function in a property of the object, then call it when cancelling the timer.

class Delayer {
  timeoutId = null;
  resolve = null;
  cancelDelay() {
    if (this.timeoutId) {
      clearTimeout(this.timeoutId);
      this.resolve();
    }
  }
  delay(ms) {
    return new Promise(resolve => {
      this.resolve = resolve;
      this.timeoutId = setTimeout(resolve, ms)
    })
  }
}

(async() => {
  const delayer = new Delayer();
  document.getElementById("b").addEventListener("click",
    () => delayer.cancelDelay());
  console.log("Starting");
  await delayer.delay(10000);
  console.log("Done");
})();
<button id="b">Click to cancel timer</button>

  • Related