Reputation: 1427
I'm trying to create a countdown timer for a prize competitions website but the time seems to only show 1 output and does not decrement by a second like it should. The console.log is also only showing one output.
Here are my methods:
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";
});
}
And here is the 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>
Upvotes: 0
Views: 337
Reputation: 89344
You are currently assigning the return value of countdown
to setInterval
instead of the function itself to be used as a callback. To keep the this
reference, you can either use an arrow function or Function#bind()
.
setInterval(()=>this.countdown(), 1000);
//or
setInterval(this.countdown.bind(this), 1000);
Upvotes: 2