ketom ketom - 1 month ago 23
Javascript Question

Vue.JS countdown not works

I have a vue application, but the countdown not work good.
Actually i dont know why.

View

{{ $parent.timer }}
i see the good value.

Vue data:

data: function() {
return {
timer : 3,
...


and here is my countdown function:

countdown : function(time,callback)
{
//time is equal 5
this.timer = time;
//this.timer is equal 5
var timerInterval = undefined;

timerInterval = setInterval(function() {
if(this.timer == 1) {
this.timer = 0;
callback();
return clearInterval(timerInterval);
}
// First time undefined, in 2nd is NaN
this.timer -= 1;
// NaN
}, 1000);
}


call function:

this.countdown(data.time,function(){ //smtng });


What i do bad? Its work in my older Vue application.

I hope someone can help to me :)
Thanks so much!

Answer

It is an issue with scope of this, as explained below:

function() {...} creates a new scope inside. If you use this inside this function, it does not refer to outer scope. Therefore your this.timer of Vue component does not get updated from inside your setInterval().

() => {...} works like a function but does not create a new scope inside.

Check if the following code works:

timerInterval = setInterval(() => {
    if(this.timer == 1) {
        this.timer = 0;  // `this` points to the scope of Vue component
        callback();
        // ...
    }
    // ...
}, 1000);

More info on arrow functions: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions