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

Enhancing code readability in vim with custom Javascript syntax highlighting

Is anyone else experiencing issues with VIM's syntax highlighting for Javascript? I have noticed that at times, the highlighting seems to disappear and I have to scroll around to get it adjusted properly. Does anyone know of any workarounds or soluti ...

Having trouble with my ASP.Net OnClick Subs not functioning as desired

I have implemented onClick handlers to process button clicks that query SQL. The issue I am facing is that these queries sometimes take between 10 to 30 seconds to return a response. To prevent click-stacking during this time, I disabled the buttons. Howev ...

The CSS toggle feature in the React component is not being implemented as expected

I am currently working on a component that maps over an array and displays a series of buttons that render specific content: export const Bookings = ({bookings}) => { const [selectedBooking, setSelectedBooking] = useState(false); const handleSel ...

Registration of Laravel Vue.js components

I am currently working on a Vue.js application in conjunction with Laravel. To get started, I registered Vue.js like this: import Vue from 'vue'; import VueRouter from 'vue-router'; Vue.use(VueRouter); import App from './compone ...

Looking for assistance with deleting a child element in an XML file using PHP

I need help figuring out how to delete a child from my jobs.xml file with a PHP script. My jobs.xml file looks like this: <jobs> <event jobid="1"> <title>jobtitle</title> <desc>description</desc> &l ...

Socket.io connects two clients together in a room

Currently, I am working on integrating private messaging functionality into an app I am developing using express 3 and socket.io. Upon a client connection, a room is automatically created and joined based on the client's user id. This feature serves ...

A guide to resolving the Postgres issue: "The bind message provides 8 parameters while the prepared statement "" only needs 6."

In my backend setup, I am working on preparing my model. I have tab1 which contains id and col: t1 that I want to insert into first, then get its id and insert it into my tab2 along with other cols. The foreign key from tab1 (id_tab2) is used in tab2 (whic ...

The AJAX response containing jQuery is failing to produce any visible changes

On Page 1 of my website, there is a form that, upon submission, loads Page 2 using jQuery. This process involves calling a PHP page and displaying the output on Page 1 without actually reloading the entire page. To maintain security, I have set up session ...

Retrieving Records within a Specific Date Range for Check-ins and Check-outs

Our team is currently working on developing booking software that requires handling different room pricing based on specific dates. Each room has distinct pricing for weekdays and weekends. ROOM 1 Pricing 1: September 1st - November 3rd, Weekday: $100, W ...

What is the method for implementing an Inset FAB with Material UI in a React project?

Currently, I am working on a project that requires an "Inset Fab" button to be placed between containers. After referencing the Material Design documentation, I discovered that the component is officially named "Inset FAB". While I was able to find some tu ...

When the browser's back button is clicked, no action occurs with Next/router

I am confused about why my page does not reload when I use the browser's back button. On my website, I have a catalog component located inside /pages/index.js as the home page. There is also a dynamic route that allows users to navigate to specific p ...

Can someone guide me on how to extract checkbox values in a post method using Angular

I'm facing an issue with a table that contains a list of rules. Whenever the checkboxes are clicked, I want them to send a "true" value to an API endpoint. However, I keep receiving an error stating that the "associated_rule" is undefined. After tryi ...

Trigger a Tabulator event when a checkbox is selected in Vue 3

Currently, I am utilizing Vue3 along with Tabulator (5.2.7) to create a data table using the Composition API. In the following code snippets, I have excluded irrelevant parts of the code. //DataTable.vue <script setup> import { TabulatorFull as Tabu ...

Prevent user input when an alert window is open

Users keep pressing the enter key multiple times when an alert box pops up, causing them to accidentally dismiss the message by hitting 'ok'. Is there a simple way to prevent key presses on alert windows and only allow mouse input? ...

What could be causing the data in Vue Dev Tools to not update properly?

Can someone clarify why this scenario wouldn't function properly in Vue? HTML <div id="app"> <button v-on:click="isActive = !isActive">Click me</button> </div> JS vueApp = new Vue({ el: '#app', data: { ...

"Looping through each item in a list using Angular

I have a setup for an HTTP request that will return the list of products once all promises are fulfilled. My objective is to initially set the opacity of these products to 0, and then use a forEach loop to add a class that sets their opacity to 1. While ...

Converting an array of objects to an array based on an interface

I'm currently facing an issue with assigning an array of objects to an interface-based array. Here is the current implementation in my item.ts interface: export interface IItem { id: number, text: string, members: any } In the item.component.ts ...

Tips for customizing the time selector in material-ui-time-picker

Is there a way to enable keyboard input control for the material-ui-time-picker? Currently, it only allows editing when clicking on the clock interface. Here is a snippet of my code: import React, { Component } from "react"; import { TimePicker } from " ...

Waiting for a webpage to fully load with JavaScript in Selenium

I am facing an issue where I need to wait for the page to fully load before executing a certain action. It is important for me that the loading circle on the browser tab stops spinning before proceeding. The current Ajax function I am using does not work c ...

Emphasize the search term "angular 2"

A messenger showcases the search results according to the input provided by the user. The objective is to emphasize the searched term while displaying the outcome. The code snippets below illustrate the HTML and component utilized for this purpose. Compon ...