如何使倒数计时器功能可重复使用

时间:2018-10-03 21:16:36

标签: javascript vue.js vuejs2

我具有如下倒计时功能:

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)来调用倒计时函数,以便每次调用此函数时都从所需的时间开始计数。如果我调用countdown方法,它将在第二次倒数工作之前计数为0。我该怎么做才能使其可重用?

1 个答案:

答案 0 :(得分:1)

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

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