Search code examples
javascriptvue.jscountdowntimer

Why does my countdown function run to quickly?


I have a countdown function in vue.js that updates too fast.

Here is the data section

data() {
        return {
            selected: [],
            countdown: timerLimit
        }

Below is the countdown method

countdownTimer() {
        this.countdown = 60;
            var downloadTimer = setInterval(() => {
            if(this.countdown <= 0){
                clearInterval(downloadTimer);
                if (this.thisUser.captain) {
                        Store.submitTurnEnd();
                    }
            }
            this.countdown -= 1
            console.log(this.countdown)
            }, 1000);
        },

Which gets called above. However, I notice after clicking a few times, it often goes too fast. I think I need to update the data section but am unsure how to.

Thanks for the help.


Solution

  • It could help you whit another variable in data:

    data() {
            return {
                selected: [],
                countdown: timerLimit,
                isCountdownActive: false
    }
    

    Method:

    countdownTimer() {
            // exit method if it is active
            if(this.isCountdownActive == true) return;
    
            // first time set ttrue
            this.isCountdownActive = true
    
            this.countdown = 60;
                var downloadTimer = setInterval(() => {
                if(this.countdown <= 0){
                    clearInterval(downloadTimer);
                    if (this.thisUser.captain) {
                            Store.submitTurnEnd();
                    }
    
                    // On exit interval, restart to false 
                    this.isCountdownActive = false
                }
                this.countdown -= 1
                console.log(this.countdown)
                }, 1000);
    },