javascript - 如何使倒数计时器功能可重复使用
问题描述
我有一个倒计时功能,如下所示:
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)
}
}
推荐阅读
- c# - UWP 理想线程数
- db2 - db2 sql在使用min时不返回最小值
- javascript - API 调用有效,然后分派返回它不是函数
- javascript - JavaScript:如何使用 innerHTML 在多列中呈现数据
- sql - 即使不存在数据,也显示每个分区的所有类别
- python - 从索引列表访问多维 np.array 的元素
- twitter-bootstrap - Twitter Bootstrap,将第三个 md-6 列集中在中型设备上
- kubernetes - Terraform dial tcp 192.xx.xx.xx:443: i/o timeout error
- sql-server - 如何配置 AKS 部署以使 ASP.NET 应用能够连接到 Azure SQL 数据库
- python - Dockerfile 中的 WORKDIR 指令在容器化 Python 应用程序时无效