首页 > 解决方案 > 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>

标签: javascriptvue.js

解决方案


您当前正在分配 to 的返回值countdownsetInterval不是函数本身以用作回调。要保留this参考,您可以使用箭头函数Function#bind().

setInterval(()=>this.countdown(), 1000);
//or
setInterval(this.countdown.bind(this), 1000);

推荐阅读