Home > Enterprise >  Not executing setInterval every time
Not executing setInterval every time

Time:01-09

I am making a stopwatch. I want to display the interval between the time the start button is pressed and now in a p tag at any moment. I tried this:

watch() {
      const p = document.createElement("p");
      p.id = "p";
      document.body.appendChild(p);
      document.getElementById("p")!.innerHTML = this.stop();
   }
   start() {
      if(this.status === 'started') throw new Error('already started');
      this.currentTime = Date.now();
      this.interVal = setInterval(() => this.watch(), 100);
      this.status = 'started';
      return this.interVal;
   }
   stop() {
      if(this.status === 'stopped') throw new Error('already stopped');
      this.duration = Date.now() - this.currentTime   this.duration;
      console.log(this.duration);
      this.status = 'stopped';
      return this.duration;
   }

CodePudding user response:

That setInterval() is repeatedly calling the this.watch() method, which subsequently calls the this.stop() method each time.

In the this.stop() method, you always set this.status = 'stopped' before returning. However, at the beginning of the method, you also check that if the status is equal to 'stopped', then you throw an Error. As a result, this.stop() can only be called once, because the first invocation sets this.status to 'stopped', which causes an Error to be thrown on every following invocation. And since this.watch() doesn't "catch" any thrown errors, the error will continue to bubble up, and this.watch() never finishes executing, therefore never updating the innerHTML.

I'm not entirely sure what your goal is, but to prevent the error from occurring, remove the line if(this.status === 'stopped') throw new Error('already stopped'); from this.stop().

  • Related