Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

Kieran_st's avatar

Vuejs Component with Timer - not ticking

Hi guys, I'm trying to make a countdown timer for a quiz using setInterval(). The interval ticks once, but then no longer executes.

Here is some code snippets to demonstrate:

HTML

<script type="text/javascript">
        var timerObj;

VueJS Component

    methods: {
        startTimer(){
                timerObj = window.setInterval(this.timerTick(), 1000);
                this.timerFormat();
            },

            stopTimer(){
                window.clearInterval(timerObj);
                timerObj = null;
            },

            timerTick(){
                if (this.timerLength != 0) {
                    this.timerLength -= 1;
                    this.timerBarWidth();
                    this.timerFormat();
                } else {
                    this.stopTimer();
                    // Some broadcast stuff to disable answering
                }
            },

            timerFormat(){
                let minutes = Math.floor(this.timerLength / 60);
                let seconds = this.timerLength % 60;

                if (seconds < 10){ seconds = "0"+seconds; }
                if (minutes < 10){ minutes = "0"+minutes; }
                this.timerDisplay = minutes + ":" + seconds;
            },

            timerBarWidth(){
                let amount = 100/this.timerseconds;
                this.timerWidth -= amount;
            }
        },

    mounted(){
            if (this.timer == "true"){
                this.startTimer();
            } else {
                this.timerWidth = 0;
            }
        }

The timerTick() function executes once, and then nothing else happens.

Some values for these variables

timerLength = 120 (seconds)
timerWidth = 100 (%)
timeDisplay = "" (graphical display: 02:00 etc)

I initially had the timerObj as a data() variable, but I thought maybe the issue was the scope, so I pulled the variable out to the global scope, but it's still not working.

I've also tried substituting for a setTimeout(), it has the same issues.

Is there something I'm just missing or doing wrong? or is there some other gremlins at play here?

0 likes
2 replies
Kieran_st's avatar
Kieran_st
OP
Best Answer
Level 9

Ah, that was the issue.

I had window.setInterval(this.timerTick(), 1000); when I really needed window.setInterval(this.timerTick, 1000);

Those damn parentheses

1 like
Progeny's avatar

Oh my. You saved my 1,5 work time days, I didn't able to find solution. Building timer with start/stop function, and your solution worked like a charm. This global timerObj variable worked like a magic.

Please or to participate in this conversation.