The accumulation of input using setInterval is not effective

I need some help with my code. Please take a look at this link here. I want the input to count up from zero and hide when I click the "change" button. But when I show the input again, I want its value to reset back to zero. Can anyone guide me on how to achieve this?

<script src="//unpkg.com/vue/dist/vue.js"></script>

<div id="app">
  <input :value="change" v-if="val1">
  <br/>
  <button @click="switchOn">Change</button>


</div>

var Main = {
    data() {
      return {
        val1: false,
                val2: 0,
      }
    },
    methods: {
    switchOn(){
    this.val1=this.val1==false?true:false
    },
    addUp(){
    setInterval(function(){this.val2++},2000);
    }
    },
    computed:{
    change(){ this.addUp(); return this.val2; }

    }
  }
var Ctor = Vue.extend(Main)
new Ctor().$mount('#app')

Answer №1

Essentially, in this scenario, the utilization of clearInterval is necessary to halt the interval that has been initiated and reset the counter back to zero.

console.clear()
var Main = {
  data() {
    return {
      val1: false,
      val2: 0,
      interval: null
    }
  },
  methods: {
    switchOn(){
      this.val1 = !this.val1
      if (!this.val1){
        clearInterval(this.interval)
        this.interval = null
        this.val2 = 0
      } else {
       this.addUp()
      }
    },
    addUp(){
      this.interval = setInterval(() => this.val2++, 2000);
    }
  },
}
var Ctor = Vue.extend(Main)
new Ctor().$mount('#app')
<script src="//unpkg.com/vue/dist/vue.js"></script>

<div id="app">
  <input v-model="val2" v-if="val1">
  <br/>
  <button @click="switchOn">Change</button>
  {{val1}}: {{val2}}

</div>

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

Properly handling the use of single and double quotation marks in variable declarations within a JavaScript file

I have a search box where users can enter their search text. For example, they can type book, 'book', or "book". The value entered in the search box is then assigned to a variable in the JavaScript file. var searchTerm = "${searchTerm}"; <br/ ...

Preload-webpack-plugin does not support pre-fetching files

I have a query about prefetching and preloading content. In my vue app, I noticed that after building, I have duplicate files loaded in my dist/index.html file. Here is an example: Additionally, the "scripts" are not being preloaded/prefetched as expec ...

Tips for managing image uploads while incorporating pre-set error detection into a form

I'm facing a challenge with integrating an optional image upload feature into my express app. The issue seems to be related to the way I've structured the app, as it appears to be trying to pass the image name from the body instead of utilizing t ...

Retrieve the function-level variable within the while loop's else statement

Struggling with node.js, I find myself facing the challenge of accessing a variable declared at the start of a function from an else statement nested within a do while loop: function myFunction(){ var limit = 2000; var count; var total; va ...

How can I update the value of a span element that was added to the HTML document through an AJAX request?

When a modal is triggered on click, data is added to it through an AJAX request to a PHP file. After the AJAX call, I want the values in span elements within the modal to change simultaneously with the input field of the modal. I attempted this JavaScript ...

In what ways can you toggle the visibility of table rows and data dynamically with the onchange event in HTML?

I'm dealing with an HTML code that can dynamically change table data based on user selection. Here's the snippet of my HTML code: Select an option: <select name='set' id="set" class="selectpicker" onchange='displayFields(this. ...

angular and node: troubleshooting the $http.get error

I have encountered an issue with the $http.get instruction. Without it on the main page, I receive a result of "random 46" which is correct. However, when I include $http.get, I get a result of "random {{ number }}". How can this problem be resolved? -se ...

Retrieve the Javascript variable and assign it to a PHP variable

When attempting to assign a JavaScript variable to a PHP variable and output the value in an alert, I am encountering an error. The output is shown as "; alert(simple); var p1sds = "My Custom String"; <?php $dsfd = "<script>document.writeln(p ...

What is the best way to use ReactJS to remove the last 3 characters from a selected text?

How can I display text on a webpage while cutting off the last 3 characters? For example, Python%22 should be displayed as Python I attempted to use substring() but it doesn't seem to be working correctly. Any help would be greatly appreciated! rende ...

Having trouble with Ajax.updater?

I am a JavaScript newcomer and currently facing an issue with prototypes. I am attempting to update sample.jsp using Ajax.updater after it is loaded, but for some reason, it's not working. Here is the source code of sample.jsp: <%@page contentTyp ...

When using Vue.js, emitting an array to a child component, mapping that array in the child, and then emitting an event to the parent may cause the developer tool to display that the

Passing the array drinks as props to Drinks.vue and mapping elements inside of it. When clicking the button, it should emit an event to change the element to 'Sold Out'. However, although the drinks array is updated according to console.log or Vu ...

The angular datepicker functionality seems to be malfunctioning

unique-example encountering this error message: error TS2307: Cannot find module 'mydatepicker' also encountering a compile time error at this line: import { MyDatePickerModule } from 'mydatepicker'; report.module.ts : import ...

Automatically increase the height of a text area as you type beyond the maximum width limit

Is there a way to dynamically expand the textarea width as I type beyond its maximum set width without displaying a horizontal scrollbar? Here is the HTML code in its rendered form: <textarea name="CatchPhrase" class="inp ...

What is the best approach for rendering content to a page in ReactJS when a user clicks on a dynamic URL?

One challenge I am currently tackling is how to direct users to a specific page when they click on a dynamic URL. Specifically, within my "product_list" API data, there exists a key called "url". Upon clicking this "url", the user should be redirected to a ...

Bringing in a script and invoking a function on a specific variable

As a newcomer to Typescript, I've been experimenting with some code I came across online to enhance the appearance of links on my website. <script src="https://wow.zamimg.com/widgets/power.js"></script> <script>var wowhead_tooltips ...

Can we retrieve the body from an Axios post request catch block?

When sending a post request to the API using axios, I receive a response of type "xhr" with an error message in the console: axios.post('https://api.myapp.com:8000', formData).then(function (response) { }).catch(function (error) { console.lo ...

Elevate your website's design with Vue and create eye-catching CSS

I've been working on a Vue hamburger menu component, but I'm facing an issue with the animations. The animation process seems to reach the desired end result, yet there is no actual animation displayed. The animation triggering is done through a ...

The Intersection Observer API is not compatible with using transform: translateX()

After successfully implementing the Intersection Observer API on my website and incorporating a few transitions from an example I came across, everything seemed to be working smoothly. You can view the scale-in transition in action here: https://jsfiddle.n ...

Switch the appearance between two elements

In my HTML table, I have different levels of content - from main "contents" to nested "sub-contents" and even deeper "sub-sub-content". My goal is to hide all sub-content within the content cell that I click on. <table> <tr class=' ...

Does the unique identifier of the element remain constant in jQuery?

For example: $("#savenew").live('click', function(e) { var user=<?php echo $user?>; $.ajax({ type: "POST", url: "actions/sub.php", data:{user: user} , ...