首页 > 解决方案 > 如何使倒数计时器功能可重复使用

问题描述

我有一个倒计时功能,如下所示:

data(){
    return {
        timer: null
    }
}

methods: {
    countdown: function(time){
        const TIME_COUNT = time;
        if (!this.timer) {
            this.count = TIME_COUNT;
            this.timer = setInterval(() => {
                if (this.count > 0 && this.count <= TIME_COUNT) {
                    this.count--;
                }
                else{
                    clearInterval(this.timer);
                    this.timer = null;
                }
        }, 1000);
}

我想用不同的参数调用倒计时函数,比如countdown(10)或者countdown(60)这样每次我调用这个函数时,它都会从我想要的时间开始计数。如果我调用倒计时方法,它将在第二个倒计时开始之前计数为 0。我应该怎么做才能使其可重复使用?

标签: javascriptvue.jsvuejs2

解决方案


这应该让您实例化多个倒计时实例函数。

const methods = {
  countdown: (time) => {
    let timeRemaining = time;
    let timer;
    timer = setInterval(() => {
      if (timeRemaining > 0) {
        timeRemaining--;
      } else {
        clearInterval(timer);
      }
    }, 1000)
  }
}


推荐阅读