Updating a value within a VueJS watcher without interfering with the watcher itself

I created a quiz application using Vue where each question has its own time limit. I implemented a countdown feature with a watcher to display the remaining time on the webpage. However, I encountered an issue when updating the time limit for the next question - the countdown would end prematurely. How can I modify the watcher to update the time limit seamlessly without disrupting the ongoing countdown?

watch: {
    timerEnabled(value) {
      if (value) {
        setTimeout(() => {
          this.timeLimit--;
        }, 1000);
      }
    },
    timeLimit: {
      handler(value) {
        if (value >= 0 && this.timerEnabled) {
          setTimeout(() => {
            this.timeLimit--;
          }, 1000);
        }
        else{
          // Update the timer for the next question and proceed to the next one
        }
      }
    }
  }

Answer №1

In my opinion, a possible solution could look like the following:

data() {
  return {
    timer: null,
    timerCounter: 0
  }
},
methods: {
  setTimer(state) { // true enabled, false disabled
    if(state) {
      this.timerCount = // seconds
      this.timer = setTimeout(() => {
        timerCounter--;
        if(timerCounter <= 0) {
          this.setTimer(false);
          // go to next question
          this.setTimer(true);
        }
      }, 1000);
    } else {
      clearTimeout(this.timer);
    }
  }
}

To start the timer for the first time, you simply need to call setTimer(true), for instance in the mounted() function or at the click event of a button.

If you prefer that the timer does not restart after changing questions, just remove this.setTimer(true);.

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

Using Vue3 to implement real-time synchronization with Ace Editor on v-model updates

I have integrated Ace Editor with Vue3 using the Vue3 Ace Editor plugin: <v-ace-editor v-model:value="currentRecord.prompt" lang="json" theme="textmate" style="height: 100%;" :options="{ ...

JavaScript's counterpart to getElementById for Classes

Currently in the process of developing a game, I am faced with the task of modifying the CSS values for an entire group of objects. When dealing with a single ID, I typically use document.getElementById("idHere"); however, now I am searching for somethin ...

Saving form blueprints and operations in a Data Repository

My team and I are working on a sophisticated web application with a complex back end. We have hundreds of form schemas paired with their corresponding return functions, which are triggered upon form submission. These JSON objects dynamically generate forms ...

Encountering an error stating 'Chart name not found' while attempting to utilize chart.js

For days now, I've been struggling with an annoying issue in chart js. I've tried every possible solution but have not been able to figure it out. The problem arises from using a TypeScript environment with ES modules. I attempted to import Char ...

Implementing dynamic drop-down menu changes with JavaScript

Looking to dynamically populate a dropdown menu with options based on the selection in another menu. Specifically, when "Audi" is selected, I want to trigger a JavaScript function that correctly populates the second dropdown with Audi model options. Howe ...

Isotope data-filter not working properly following an Ajax callback

I'm looking for a way to create a filter that can be dynamically updated: I have utilized the isotope javascript library in an external script file: var $container = $('.isotope'); // initialize isotope $container.isotope({ ...

What is the correct way to integrate nested forms using Validator and Control Value Accessor?

One challenge in my application is the need for a reusable nested form component like Address. I wanted my AddressComponent to manage its own FormGroup without the need for external input. During an Angular conference (video, presentation), Kara Erikson f ...

Leveraging ReactDOM.render within a component

My issue is quite unique - I need to render components with different IDs on a website, but I can't render all the content under one ID. I've managed to fetch a JSON array through a GET request and have set up a loop for each item in the array. ...

Using three.js to input text instead of particles within a particle cloud

I have a unique three.js codepen project where square particles drift through the space. However, I am now looking to enhance it by incorporating text (perhaps using geometry?) instead of the square particles, creating a word/tag cloud effect. Is this eve ...

Tips for accessing key-value arrays in PHP sent via Ajax POST requestsHow to effectively retrieve key-value pairs

Is there a way to access a key and value array passed through an ajax call to a PHP function on the PHP side using the $_POST method? var eImages = [{ ProductID: ProductID, Image: image1Name, ImagePath: image1Path }, { ProductID: Produc ...

Browsing across pages seamlessly without the need to refresh the browser

I need help with making my admin panel built using Bootstrap and integrated with Laravel navigate through tabs without refreshing the browser. Can anyone provide guidance on how to modify the code to achieve this functionality? You can check out the admin ...

The second AJAX request fails to execute

I'm facing an issue with a simple voting button that only works once per post per page reload. The desired functionality is as follows: Click on "+" -> update query (in django) -> refresh a div (changing "+" to "-") -> allow clicking "-" t ...

Implementing a heart icon that instantly registers a user's approval without the need for a page reload

Seeking advice on incorporating a like button into my RoR application for posts. The Post and Like models are already in place. The plan is to position the like button alongside the post button, with a desire for the user's click on the like button t ...

How do I implement a filtering system in Vue.js for products based on size, color, and category? Is it possible to create a step-by-step slider for selecting each

How can I use vue.js to implement a filtering system for products based on size, color, and category? I want users to be able to select each filter one by one in a step-wise slider interface. Once all filters are chosen, the products that meet the criter ...

Generating arrays and datasets using the power of JavaScript and jQuery

Recently, I wrote a code to arrange points inside a table, and everything was working perfectly when I specified an arrayOfDivs: http://jsfiddle.net/u58k6/6 var arrayOfDivs = [({topPosition : 99, leftPosition: 100}),({topPosition : 150, leftPosition: 400} ...

Securing text field content in Ext JS from exposure to HTML and Selenium

Recently, I've been working on automating test cases using Selenium2 Java for an application that heavily utilizes ExtJS. Despite successfully handling the changing element ids, there is one specific page where I'm facing a puzzling issue. There& ...

Recursion functions seem to be not providing a return value

I wrote a recursive function that needs to return an object from an array of objects. Each object in the array includes a reference to a neighboring object, as shown below: { id: 5, neighbors: { north: 1, east: 6, south: 9, west: 4 ...

Utilize Vue js on Laravel to modify the WP REST API Date representation

Hey there! I'm trying to display the date my post was created in WordPress using Vue.js. Currently, it's showing up in a weird format like this: 2018-08-06T18:29:59 Here is the code I have in my .vue file: <div class="date-below"><p ...

What is the solution for the error message: "[Vue warn]: Error in mounted hook: 'TypeError: document.getElementById(...) is null'" that appears in the <Root> component?

I'm facing an issue with a checkbox in my Vue.js application. Whenever the user checks this checkbox, the data property accepted changes from false to true. My goal is to hide certain HTML elements when accepted = true. I have been attempting to achi ...

Retrieve a parameter from jQuery and pass it to a JavaScript function

Currently, I am working with Puppeteer and encountering an issue where the "selector" is undefined when calling this function. async function checkIfTextIsPresent(page, selector){ let myElement = await page.evaluate(() => document.querySelector(sel ...