javascript - setInterval 不每秒更新 DOM
问题描述
我正在尝试为一个有奖竞赛网站创建一个倒数计时器,但时间似乎只显示 1 个输出,并且不会像它应该的那样减少一秒。console.log 也只显示一个输出。
这是我的方法:
getClosingCompetitions() {
this.$axios({
method: 'get',
url: 'http://rafflear.test/api/get-closing-competitions',
config: { headers: { 'Content-Type': 'application/x-www-form-urlencoded' }}
})
.then(response => {
this.closingComps = response.data;
setInterval(this.countdown(), 1000);
})
.catch(e => {
this.errors.push(e)
})
},
countdown() {
this.closingComps.map((e, index) => {
let now = moment();
let expiration = moment(e.end_date);
let diff = expiration.diff(now);
let diffDuration = moment.duration(diff);
this.timer[index] = diffDuration.days() + " days " + diffDuration.hours() + " hours " + diffDuration.minutes() + " mins " + diffDuration.seconds() + " secs";
});
}
这是 DOM:
v-row>
<v-col v-for="(item, index) in closingComps" :key="item.id" md="3">
<v-card class="pa-2 latest-competitions">
<span class="text-caption">
{{ timer[index] }}
</span>
</v-card>
</v-col>
</v-row>
解决方案
您当前正在分配 to 的返回值countdown
而setInterval
不是函数本身以用作回调。要保留this
参考,您可以使用箭头函数或Function#bind()
.
setInterval(()=>this.countdown(), 1000);
//or
setInterval(this.countdown.bind(this), 1000);
推荐阅读
- python-3.x - Pyspark 使用 pyodbc 连接到 sqlserver 在集群模式下失败(部署模式)
- javascript - Python JS 当前时间
- javascript - 使用未捕获的 ReferenceError: $ 未定义
- javascript - 将字符串格式转换为日期格式 JS
- python - 从 python 发送电子邮件
- javascript - Mocha 测试:不能在模块外使用 import 语句
- javascript - 无法通过 URL 将变量从 javascript 文件传递到 php 文件
- openid - OpenID 客户端提供者
- javascript - 当其中有冒号和下划线时,似乎无法按 ID 选择元素
- javascript - Javascript - 从过滤器中删除数组中的对象