The Vue countdown timer speeds up when the watched variable is modified from a method

Recently delved into Vue and JS. I've implemented a watcher for a timerCount variable (initialized to 5) that triggers a 5-second timer. When the variable reaches zero, certain code is executed, and then I reset the timer to 5 to start over. Everything works as expected, but when a click event invokes a method which executes different code and resets the timer to 5, the timer speeds up (twice as fast).

After doing some research online, it seems like there are multiple instances of watchers/timers running simultaneously, causing the acceleration. How can I resolve this issue so my method simply resets the timer normally?

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 now it runs twice as fast, unsure why.
    otherMethod(){
        /* Code */
        this.timerCount=5
    }

}

Any suggestions on how to solve this dilemma?

Referenced source: How do I create a simple 10 seconds countdown in Vue.js

Answer №1

When coding, if you're observing timerCount, any changes made to that variable will trigger Vue to watch it again when running otherMethod. This means the watcher and its handler will run repeatedly every time timerCount is updated.

Instead of using a watcher, you could initiate your timer in the created event using setInterval (not setTimeout). setInterval executes your code at intervals, but not strictly every 1000ms - it could be slightly more or less.

You can create a function inside setInterval with a delay of around 100ms, allowing you to track whether 5 seconds have passed or not.

Answer №2

Implement a function called initializeWatcher() that sets up a watcher and stores the watcher instance in a data variable. Invoke the initializeWatcher() function during component creation. Whenever you need to make changes to the watched variable, first stop the watcher, update the variable, and then create the watcher again. (refer to whenUpdatingVariable())

For more information, check out the documentation on creating watchers and stopping watchers

data(){
 return{
  myWatcherInstance: null,
  timerCount: 10
 }
}
methods: {
 whenUpdatingVariable(){
  // stop watcher/unwatch
  this.myWatcherInstance();

  // update variable
  this.timerCount = 20;

  // create watcher again
  this.initializeWatcher();
 },
 initializeWatcher(){
    this.myWatcherInstance = this.$watch('timerCount', () => {
        setTimeout(() => {
          this.timerCount--;
        }, 1000);
      })
    }
  }
},
created(){
 this.initializeWatcher();
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a glitch in the console when sorting an array of dates?

I'm puzzled by the fact that the console is displaying a sorted array in both logs. It doesn't make sense to me because it should not be sorted at the first log, right? static reloadAndSortItems() { let array = []; const items = Store. ...

Send the user to the chosen option in the dropdown menu

My goal is to redirect the user based on the option they select. I am having an issue with my HTML code as it currently redirects to "example.com/page" instead of "example.com/page/1". Can someone please assist me in resolving this problem? <select clas ...

issue concerning slide functionality and ajax integration

I'm facing an issue with the structure of my HTML. Here is the setup I have: <div id ="slide1"> <form method="post" id="customForm" action=""> //my content - name, email, mypassword, pass2 </for ...

Issues with 'md-sidenav' in AngularJs failing to respond to click event in Firefox

Currently, I am working on an Angular project that includes a sidenav based on the specifications of AngularJS Material Design. Everything seems to be functioning correctly when I click on the menu icon to control the sidenav in Chrome and other major brow ...

Feeling lost about arrow functions in JavaScript

Here is the code I am currently using to increment the value of intVariable using window.setInterval. var Arrow = (function () { function Arrow() { this.intVariable = 1; this.itemId = -1; this.interval = 25; } Arrow.p ...

Struggling to retrieve user input from a textfield using React framework

I'm having trouble retrieving input from a text-field in react and I can't figure out why. I've tried several solutions but none of them seem to be working. I even attempted to follow the instructions on https://reactjs.org/docs/refs-and-th ...

Attempt running the Vuetify documentation on your local machine

I have been trying to access the Vuetify docs on my local Mac. Following the instructions in this post: cd /tmp/ git clone https://github.com/vuetifyjs/vuetify.git cd vuetify/packages/docs yarn # option 1 - build and serve yarn build yarn start # optio ...

How to dynamically insert a new row below a specific row with a sliding animation in jQuery

My task is to create a tree-like table structure where clicking on a specific row will reveal and add new rows below it. Specifically, I am designing the Category and SubCategory structure. Currently, I can append rows after a specified row but am struggl ...

NextJS configuration facing an issue with rewrite rules not functioning as intended

I have attempted to utilize a rewrite rule in the NextJS next.config.js file in order to redirect URLs containing '/lite' to '?amp=1', however, it does not seem to be functioning correctly in all scenarios. Below is the code from my ne ...

Obtaining the initial variable from an array - a simple guide

Although it seems simple, I am having trouble getting it to work. I have an array with 2 variables inside that I retrieve from jQuery. var features = [long, lat ] I want to iterate through all the values in the loop and use: fetures[i] This should give ...

Adding images to your SVG using Bobril is a simple process that can add visual

I have been attempting to insert an image into an SVG using Bobril, but the following code is not functioning as expected: { tag: 'svg', children: { tag: 'image', attrs: { 'xlink:href': &ap ...

Modify the content and display of a stationary div based on vertical positions

I am interested in creating a vertical website that features multiple divs appearing at specific y-points on the page. These divs will contain text and will always be positioned fixed at 20% from the left and about 250px from the top. My goal is to have t ...

Troubleshooting issue: Click function not responding inside Bootstrap modal

Below is the JavaScript code for my click function $(".addPizza").on("click", function(event) { event.preventDefault(); console.log("hello") let userId = $("#userId").attr("data-id"); let pizzaRecipe = $('#pizza-recipe').val().trim(); ...

What is the reason behind the need to provide the complete string in my 'includes' statement?

Within my Node JS project, I am attempting to utilize an 'if includes' statement to filter the results extracted from a .txt file. The goal is to correlate the serial number entered by a user with specific models based on the first 5 numbers. I w ...

What is the best way for me to obtain cut documents?

I have a collection of documents similar to this: https://i.sstatic.net/s5IsG.png How can I retrieve specific fields, such as content.headline, content.description, content.tags, and id, from 11 documents using their corresponding _id values. To clarify ...

Angular fails to include the values of request headers in its requests

Using Django REST framework for the backend, I am attempting to authenticate requests in Angular by including a token in the request headers. However, Angular does not seem to be sending any header values. Despite trying various methods to add headers to ...

In the realm of ASP.NET, the Razor FormExtensions.BeginForm Method holds the

In my current view, there is a dropdown list that allows the user to select an option which will then redirect them to another page or controller. I am using JavaScript to retrieve the selected value from the dropdown list, but I am facing difficulties whe ...

My Vuex component is not updating when the state changes

My component is not reacting to Vuex store changes when I edit an existing element, even though it works fine when adding a new element. After hours of debugging and trying everything, I've realized that it might have something to do with deep watchin ...

Uploading pictures to Imgur without the need for an API key

I've been attempting to utilize the imgur API feature that allows you to upload an image by sending a GET request to http://api.imgur.com/2/upload with a URL in the form data. However, I have been unsuccessful in making it work as intended, as it simp ...

PHP array does not retain a variable

While building a website, I encountered a perplexing bug during coding. The issue arises when I store MySQL query results in an array and then call a JavaScript function with that data. Initially, the array contains 9 items: 8 of type tinyint(4) (from the ...