每次我调用setInterval方法时,我的计数器都会加速-VUEJS

发布于 2025-02-11 17:59:27 字数 649 浏览 0 评论 0原文

我正在开发一个函数调用的倒计时。目标是每次用户回答游戏中的问题时重新启动倒计时,下一个问题是实例化的。我一直面临的问题是,每次我在时间耗尽之前调用功能时,下一个倒计时会加速并跳过数字。

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

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>

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

柳絮泡泡 2025-02-18 17:59:27

经过大量的研究和尝试,我能够通过一些更改解决此问题:

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

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>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文