如何使倒数计时器功能可重用
How to make a countdown timer function reusable
我有一个倒计时功能,如下所示:
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。我应该怎么做才能使其可重复使用?
这应该可以让您实例化多个倒计时实例函数。
const methods = {
countdown: (time) => {
let timeRemaining = time;
let timer;
timer = setInterval(() => {
if (timeRemaining > 0) {
timeRemaining--;
} else {
clearInterval(timer);
}
}, 1000)
}
}
我有一个倒计时功能,如下所示:
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。我应该怎么做才能使其可重复使用?
这应该可以让您实例化多个倒计时实例函数。
const methods = {
countdown: (time) => {
let timeRemaining = time;
let timer;
timer = setInterval(() => {
if (timeRemaining > 0) {
timeRemaining--;
} else {
clearInterval(timer);
}
}, 1000)
}
}