Mathews Edwirds
Mathews Edwirds

Reputation: 75

Everytime I call the setinterval method, my counter accelerates - vuejs

I am developing a countdown called by a function. The goal is to restart the countdown every time the user answers a question in the game and the next question is instantiated. The problem I've been facing is that every time I call the function before time runs out, the next countdown gets accelerated and skips numbers.

<template>
  <div>
    {{ countDown }}
  </div>
</template>

<script>
export default {
  data() {
    return {
      countDown: 10,
    };
  },
  method: {
    countDownTimer() {
      const timer = setInterval(() => {
        if (this.countDown > 0) {
          this.countDown--;
        } else {
          clearInterval(timer);
        }
      }, 1000);
    },
    nextquestion(){
      this.countDownTimer();
    },
  },
  mounted() {
    this.countDownTimer();
  },
};
</script>

Upvotes: 1

Views: 341

Answers (1)

Mathews Edwirds
Mathews Edwirds

Reputation: 75

After a lot of research and trying, I was able to solve this with a few changes:

<template>
  <div>
    {{ countDown }}
  </div>
</template>

<script>
export default {
  data() {
    return {
      countDown: 10,
    };
  },
  created(){
  this.timer = 0;
  },
  method: {
    countDownTimer() {
      clearInterval(this.timer);
      this.timer = setInterval(() => {
        if (this.countDown > 0) {
          this.countDown--;
        } else {
          clearInterval(this.timer);
        }
      }, 1000);
    },
    nextquestion(){
      this.countDown = 10;
      this.countDownTimer();
    },
  },
  mounted() {
    this.countDownTimer();
  },
};
</script>

Upvotes: 2

Related Questions