Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

74
Vistas
Vue countdown timer using watcher accelerates when modifying watched variable from method

very new to Vue and JS. I've setup a watcher for a timerCount variable (initially set to 5) which makes a 5 second timer. When the variable hits 0, some code is executed, and I reset the timer to 5 to restart it. This works perfectly fine, however, I have a click event which calls a method, which will execute different code and then reset the timer to 5 as well, but now my timer is accelerated (twice as fast).

From what I could find from googling, it seems that there are multiple watcher/timer instances running at the same time, which is what causes the speed up. How do I fix this so my method simply reset the timer like normal?

watch: {
    timerCount: {
        handler(value){
            //timer for 5 seconds
            if (value>0){
                setTimeout(() => {
                    this.timerCount--;
                }, 1000);
            }
            //if timer hits 0, execute code and reset timerCount to 5 seconds, this works fine
            else{
                /* Code */
                this.timerCount=5
            }
        },
        immediate: true,
    }
},

methods:{
    //this resets the timer, but it now goes twice as fast, don't know why.
    otherMethod(){
        /* Code */
        this.timerCount=5
    }

}

Any help?

Here is the post where I got this code: How do I create a simple 10 seconds countdown in Vue.js

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

In you code, you are watching timerCount. When you make a change on your timeCount means, when you run otherMethod, Vue watches it then run watcher again and handler for this watcher runs again. Everytime you change timerCount variable your watcher run and again and again.

Actually without watcher you can start your time inside your created event with setInterval (not setTimeout). setInterval run your code within givin interval but not strictly 1000ms. It may be 1005ms or less.

You can create some function inside setInterval and give it like 100ms and control the time if it is passed 5 seconds or not.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda