Looping through values in VueJS from 100 to 0

I am currently working on creating a power meter that will smoothly transition from 100 to 0 and back again to 100. The idea is for the user to press a button, causing the meter to stop at a random value.

I just need some assistance in getting the loop function to work correctly.

export default {
  data() {
    return {
      
      power: 100,
     
    };
  },
}


watch:{
power: {
      handler(value) {
        if (value == 100 || value > 0) {
          setTimeout(() => {
            this.power--;
          }, 100);
        } if (value == 0) {
          setTimeout(() => {
            this.power++;
          }, 100);
        
        }
      },
      immediate: true 
    },
}

Answer №1

Perhaps there are alternative solutions available, but here is one that I thought of:

<template>
  <section v-if="!showPart">
    <!-- This section displays when the program is cycling through numbers -->
    <div v-if="power1">
      {{power}}
    </div>
    <div v-else>
      {{powerReverse}}
    </div>
  </section>
  <div v-else>
    <!-- This section displays when the user clicks to select a number -->
    {{showValue}}
  </div>
  <button @click="stopFunc">{{textBtn}}</button>
</template>

<script>
export default {
  name: "powerCompo",
  data() {
    return {
      speed: 100, // speed of loop
      power: 99, // start point of loop
      power1: true, // for changing view between increase and decrease states
      powerReverse: 0, // for increasing loop after reaching "0"
      showValue: "nothing selected", // displaying the selected value
      decrease: null, // for clearing "timeout" in decrease mode
      increase: null, // for clearing "timeout" in increase mode
      showPart: false, // for toggling between "loop" or "stop" modes
      textBtn: "click for stop" // defines the button text
    };
  },
  watch:{
    power: {
      handler(value) {
        this.decrease = setTimeout(() => {
          this.power--;
        }, this.speed);

        if (this.power === 0) {
          clearTimeout(this.decrease);
          console.log("decrease");
          this.power1 = false;
          this.powerReverse = 0;
          this.powerReverse++;
        }
      },
      immediate: true
    },
    powerReverse(newValue) {
      this.increase = setTimeout(() => {
        this.powerReverse++;
      }, this.speed);

      if (this.powerReverse === 100) {
        clearTimeout(this.increase);
        console.log("increase");
        this.power1 = true;
        this.power = 100;
        this.power--;
      }
    }
  },
  methods: {
    stopFunc: function ($event) {
      /* This function is called each time the user clicks on the button. If the button text is "click for cycling again", it calls "resetFunc()" method; otherwise, it stops looping and shows the selected value. */
      if ($event.target.innerText === "click for cycling again") {
        this.resetFunc();
      } else {
        if (this.power1) {
          this.showValue = this.power;
          if (this.showValue === 100) {
            this.showValue = 99;
            this.power = 99;
          }
        } else {
          this.showValue = this.powerReverse;
        }
        this.showPart = true;
        clearTimeout(this.increase);
        clearTimeout(this.decrease);
        this.textBtn = "click for cycling again"
      }
    },
    resetFunc: function () {
      clearTimeout(this.increase);
      clearTimeout(this.decrease);
      this.textBtn = "click for stop"
      this.showPart = false;
      this.power= 100;
      this.power1= true;
    }
  }
}
</script>

Using the above component, you can iterate between [1, 99].

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

JavaScript- Tabbed Navigation with Lists as the Content

Currently, I am facing a frustrating issue in finding a suitable solution. My website uses tabs that utilize the UL, LI system, similar to most tab systems found in tutorials. The problem arises because the javascript on my site interferes with using the ...

What makes 'Parsing JSON with jQuery' unnecessary?

Just performed an ajax request with a query and noticed that my response is already in the form of a JavaScript object. When I try to parse the JSON using: var obj = jQuery.parseJSON(response); 'obj' turns out to be null, yet I can directly ac ...

JavaScript: Discovering the art of "utilizing RESTful APIs"

After several years of coding in JS, I am now expanding my knowledge. I have noticed many job postings asking for familiarity with REST APIs and experience consuming RESTful services. I have a solid grasp on AJAX basics using both vanilla JS and jQuery. I ...

Using Javascript/JQuery to extract numbers from a URL with regex or alternative methods

I need help extracting a specific group of consecutive numbers from the following URLs: www.letters.com/letters/numbers/letters" and www.letters.com/letters/letters/numbers/symbols Is there a way to isolate only the continuous sequence of numbers in th ...

Tips for avoiding html entities in a string

To prevent any user-entered content from being interpreted as HTML, I need to escape it so that special characters like < become < in the markup. However, I still want to wrap the escaped content with actual HTML tags. The goal is to ensure that the HTM ...

Why does my POST request result in an express get being triggered?

When my express server runs the deliverCard() method, it sends a set of key/value pairs. app.get('/', (req, res) => { let card = deck.deliverCard(); console.log('get', card) res.render('layout.ejs', {element:card}); ...

Change the value of a single element in an array using a component in ReactJS

I'm attempting to pass an array value to a specific index in one component and then assign a desired value from the child component. I need it to work this way because I'm developing a survey app where the number of questions can vary. This is j ...

Inform jQuery that the draggable element is in the process of being dragged dynamically

Currently, this issue is a vital component of an ongoing task. Once we can resolve this issue, it will lead to the completion of this and another inquiry. The original objective can be found here: drag marker outside map to html element You can view the ...

personalizing material-ui component styles – set select component color to be pure white

I am looking to implement a dropdown menu using material-ui components (refer to https://material-ui.com/components/selects/). To do so, I have extracted the specific component from the example: Component return <div> <FormControl variant="outli ...

In the production mode, Nuxt styles may not be properly applied

After working on this project for about four months, everything seems fine in the development version. However, once I build the project and upload it to the server, some of my styles are not applied. For more information, I have imported styles both in c ...

To achieve the desired format, where should I press or manipulate the information?

I need help with manipulating arrays to generate a specific JSON file structure. I've made some progress but got stuck at this point: var T_nn_IN = document.getElementById('datatablenewname'); var tabledata_newname_initialname = []; ...

Why is it that when I refresh the page in Angular, my logged-in user is not being recognized? What could be causing this

I am developing a Single Page Application using the combination of Angular JS and Node JS. In my HTML file, I have defined two divs and based on certain conditions, I want to display one of them using ng-if. However, I noticed that the model value used in ...

Retrieve a targeted data value from a JSON object based on an array value

Looking at the JSON array and another array provided below. JSON OBJECT { id: 1, name: 'abc', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="dfbebdbc9fb8b2beb6b3f1bcb0b2">[emai ...

Is there a way to use AJAX for transferring a value?

I am looking to transmit a value to a php-script (servo.php) that will then write the received data in a file (/dev/servoblaster). The script section of my HTML file (index.html): <script> function tiltt() { var tilt = document.getElementById("tilt ...

Determining Adjacency of <li> Elements Using jQuery Sortable() and Class Comparison

I have created a custom display builder specifically for outdoor power equipment dealers. This tool allows them to easily add, remove, and rearrange different product display sections according to their preferences. To achieve this functionality, I utilize ...

Enhanced jQuery implementation for hiding elements

I encountered a peculiar issue where jQuery's .is(':hidden') function wrongly returned true for an element that visibly displayed content. You can see the problem demonstrated in this fiddle. The :hidden pseudo checks both offsetWidth and o ...

Utilizing server-side cookies in next.js and nest.js for efficient data storage

I have been working on a small application using Next.js and Nest.js. One of the functionalities I implemented is a /login call in my client, which expects an HttpOnly Cookie from the server in response. Upon receiving a successful response, the user shoul ...

Vue: Storing selected list values in an array

I am working on a Vue application where I need to select two elements from a list component and place them inside an array. Currently, I have my list set up with selection functionality thanks to Vuetify. I have bound the selected items to an array using v ...

Implementing Ideone API functionality on Codeigniter with the use of ajax, javascript, and soapclient

I am new to using Codeigniter and I apologize if my question is basic. I found some code on this site: Working with IDE One API (Full project code available here) and I'm attempting to incorporate it into Codeigniter. I have been able to get it worki ...

Month and year selection feature in ExtJS 4 catalog

I recently came across an interesting Fiddle that featured a Month and Year picker for apps. After finding this Fiddle here, I noticed that it was built using Extjs 5.0, and it worked perfectly. However, when attempting to switch it to version 4.2.1, the l ...