Chrillewoodz
Chrillewoodz

Reputation: 28348

Unable to resume timer at the time it was stopped

I realise there are already tons of questions on this topic but no matter how much I look at the answers there I cannot make it work in my own scenario.

I'm writing a game and got a Timer class which counts down from 60 seconds down to 0, if it reaches 0 it should end the game.

The current problem is that when calling stop and then start again at a later time, the timer will not continue from the point it was stopped. It still checks from this.startTime which is when the timer first started ticking down.

So I was like alright let me re-set the startTime property when I call stop like:

this.startTime = this.startTime - this.elapsedTime;

But that gives really strange results as well, as it makes the timer jump in an incremental manner, for example 55, 45, 30, 0 when you stop/start a few more times.

How can I tweak my stop function to make this work?

class Timer {

  player;
  startTime;
  elapsedTime;
  viewableTime;
  isPaused = true;

  constructor(player) {
    this.player = player;
  }

  create() {

    this.interval = setInterval(() => {

      if (!this.isPaused && game.state.isGameActive) {

        this.elapsedTime = Date.now() - this.startTime;
        this.viewableTime = ((60000 - this.elapsedTime) / 1000).toFixed(2);

        game.view.updatePlayerTimer(this.player);

        if (this.viewableTime <= 0) {
          this.ranOut();
        }
      }
    }, 100);
  }

  start() {

    if (!this.interval) {
      this.create();
    }

    this.isPaused = false;

    if (this.startTime === undefined) {
      this.startTime = Date.now();
    }
  }

  stop() {
    this.isPaused = true;
    this.startTime = this.startTime - this.elapsedTime;
  }

  reset() {
    clearInterval(this.interval);
    this.startTime = undefined;
    this.elapsedTime = undefined;
    this.viewableTime = undefined;
    this.interval = undefined;
    this.isPaused = true;
  }

  ranOut() {
    game.endGame(true);
  }
}

Upvotes: 2

Views: 55

Answers (1)

Szaman
Szaman

Reputation: 2388

One approach is to add a new class property remainingTime. At first, you set it as 60000. Then, in the stop() method, you subtract the elapsed time from it:

this.remainingTime = this.remainingTime - this.elapsedTime

In the start() method, you then need to remove the if condition, and just always reset the startTime to the current time, and set the elapsedTime to 0.

Note: make sure to also update your create() method, so it uses the new property, instead of the hard-coded value for remaining time.

Upvotes: 2

Related Questions