How to use VueJS to detect changes in a value and trigger animations

Within my Vue.js application, I am looking to incorporate animations for a number/value that changes dynamically based on data retrieved from the Vuex store.

Although I have managed to initiate the animation successfully, I am encountering an issue where the animation loop appears to be infinite and continues endlessly.

data() {
  return {
     interval: false,
     hitsCount: 0
  }
},

watch: {
    hitsCount: function() {
       clearInterval(this.interval);

       this.interval = window.setInterval( function() {
            let change = this.hitsCount / 10;

            change = change >= 0 ? Math.ceil(change) : Math.floor(change);

            this.hitsCount = this.hitsCount + change;
        }.bind(this),20);
    }
}

The corresponding template structure is as follows:

<div> {{hitsCount}} </div>

The value of hitsCount is sourced from an API request:

this.$store.dispatch("store/data", {}).then(response => {
    this.hitsCount = response.total;
    .../
});

As each new request is made, the value dynamically updates. Despite these adjustments, the animation cycle persists infinitely. What could potentially be causing this issue?

Answer №1

If you're changing a property, it's best not to keep an eye on it constantly. Instead, split it into two separate variables.

data() {
  return {
    hitsCount: 0,
    hitsCountDisplay: 0
  }
},

watch: {
  hitsCount() {
    clearInterval(this.interval);

    if (this.hitsCount !== this.hitsCountDisplay) {
      let value = this.hitsCountDisplay;
      const change = (this.hitsCount - this.hitsCountDisplay) / 30;
      this.interval = setInterval(() => {
        value += change;
        this.hitsCountDisplay = Math.round(value);
        if (this.hitsCountDisplay === this.hitsCount) {
          clearInterval(this.interval);
        }
      }, 20);
    }          
  }
}

Also, update your HTML code to reflect the changes:

<div> {{hitsCountDisplay}} </div>

You can view a working example of this implementation here: https://jsfiddle.net/knvyrx8j/

Answer №2

Avoid updating a property within its watcher as it may lead to an endless loop. Instead, consider triggering the animation within the callback function of your action dispatcher:

this.$store.dispatch("store/data", {}).then(response => {
    let totalItems = response.total;
    clearInterval(this.interval);

       this.interval = window.setInterval( function() {
            let change = totalItems / 10;

            change = change >= 0 ? Math.ceil(change) : Math.floor(change);

            this.hitsCount = this.hitsCount + change;
        }.bind(this),20);
});

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

How can TypeScript objects be serialized?

Is there a reliable method for preserving type information during JSON serialization/deserialization of Typescript objects? The straightforward JSON.parse(JSON.stringify) approach has proven to have several limitations. Are there more effective ad-hoc sol ...

Delving into the World of ES6 Symbols

Throughout my experience with various programming languages, from C# to Lisp to Scala to Haskell, symbols have consistently behaved as singleton objects. This means that any two symbols with the same name are guaranteed to be identical. In Racket: (equal? ...

Determine the presence of a JSON Value/Array in a web application using JavaScript and visualize the information in a dynamic

Utilizing the Ticketmaster API has provided me with a sample dataset from their platform, Data 1 - Including information on "presales." "sales": { "public": { "startDateTime": "2019-11 ...

Displaying a mouse cursor using an A-frame function

I am presently working on a scene using A-frame () in which I have hidden the mouse pointer. Is there a way for me to set it up so that when a specific function is triggered, the mouse pointer will show, and when another function is executed, the mouse poi ...

What is causing the failure of success function commands to be executed?

Currently, I am facing some inconsistencies between my locally hosted app on WAMP (working perfectly) and the deployed version of my app. In an attempt to resolve this issue, I am working with CodeIgniter and jQuery AJAX. As part of my troubleshooting proc ...

managing, modifying and removing information within the app.controller in AngularJS

I am currently facing a challenge with my Javascript code for a simple web application that involves AngularJS. Here is the snippet of code I am working on: app.filter('startFrom', function () { return function (input, start) { if (i ...

How can I make the first option in a dropdown menu automatically selected in a select input form?

Having an issue where the first selection in my dropdown list is showing as null even though it should be selected. Here is the code: <div class="form-group mb-6"> <label class="form-label">{{ $trans('labels.departme ...

Erase a set of characters with the press of the backspace key (JavaScript)

Within my textarea, I have lines that start with a number and a period: <textarea autoFocus id="text-area"wrap="hard" defaultValue ={this.state.textAreaVal} onKeyUp={this._editTextArea}/> For example: Line 1 Line 2 Line 3 I've created a ...

Navigating the process of transferring a function to a functional component within React

Hey there, I'm fairly new to using React and TypeScript and I am facing a small issue with moving a function from the file App.tsx to a functional component called WordAddingForm.tsx. Any help would be greatly appreciated! Let's start with my Ap ...

Javascript on-page scroll positioning

My current dilemma involves finding a solution to optimize in-page scrolling for mobile users. I have a sticky header on the page, which causes #section1 to place the scroll position behind the sticky header. Is there a way to adjust the scroll position b ...

Node server optimization for images

Currently, I have a server set up for uploading images. In order to enhance the image upload process, I am looking for ways to optimize it. This is my current function for uploading files: uploadImage(file, uid, res) { var fs = require('fs') ...

What steps should I take to repair this array table?

I've created a simple array table that uses 3 user-defined values to determine the value of a variable. Although I've written similar code in the past, I'm having trouble figuring out why this one isn't working. The table is quite large ...

Invoking servlet using Ajax

I have created a JSP file with Javascript functions and AJAX calls to invoke a servlet (ReadprojectInfo). <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE ...

Leveraging ES6 modules within JavaScript for exporting uncomplicated variables

In my JavaScript code, I have defined pageId = 3 in one file and socket = io() in another file. Now, I need to access these variables in other files. I am considering using ES6 modules for this purpose, but I am unsure of how to proceed. Currently, the s ...

Is using Javascript objects a better alternative to Redux?

I'm in the process of creating my initial application with React and have opted to integrate Redux into it. Since incorporating Redux, it appears that setting a component state to a basic global JavaScript object would be a simpler approach. I unders ...

Scroll horizontally through the number field in Chrome

I have configured a number input field with the text aligned to the right. Scenario: While testing, I discovered that selecting the entire text or using the middle mouse button to scroll within the input field allows for a slight leftward scrolling of ab ...

Collaborating on validating inputs and modules for both backend and frontend

Sharing input validation is crucial for various reasons: Immediate feedback to users on the frontend regarding the validity of their input Enhanced security measures in the backend, preventing manipulation of data through the API Dependency on frontend J ...

Retrieving the ID of the dragged item and its list in Vue.draggable

Despite thoroughly researching documentation and StackOverflow, I am still facing challenges with my current project. My project involves creating a Trello-like application using Vue.js and Rails. Within the app, there are multiple draggable lists. Each ...

Retrieving the headers from an ajax request

Is there a method to retrieve the complete request headers used in an AJAX call made through jQuery? ...

Shuffle the contents of various div elements, conceal one, reveal another

I am currently working with a menu that uses the loadContent function to load pages into the #main div. This allows me to change the content of the page while keeping the menu intact. <ul> <li class="page1" onclick="loadContent('page1.php ...