Clear the interval set by an object

Currently experimenting with VueJS and managed to develop a basic counter. I'm attempting to reset the setInterval() method using the resetTimer() function, but it's not functioning as expected. Unsure of what steps I might be overlooking.

new Vue({
    el: '#app',
    data: {
        hours: 0,
        minutes: 0,
        seconds: 0,
        counter: 0
    },
    methods: {
        timer() {
                setInterval(() => {
                    this.seconds = this.timerFormat(++this.counter % 60)
                    this.minutes = this.timerFormat(parseInt(this.counter / 60, 10) % 60)
                    this.hours = this.timerFormat(parseInt(this.counter / 3600, 10))
                }, 1000);
            },
            resetTimer() {
                clearInterval(this.timer())
            },
            timerFormat(timer) {
                return timer > 9 ? timer : '0' + timer;
            }
    }
})
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Learning Vue</title>
  </head>
  <body>
    <div id="app">
      <p>{{ hours }} : {{ minutes }} : {{ seconds }}</p>
      <button @click="timer">Start</button>
      <button @click="resetTimer">Reset</button>
    </div>

    <script src="dist/bundle.js"></script>
  </body>
</html>

Answer №1

To implement an interval timer, create a global variable such as my_timer. You can clear this timer in the reset action:

new Vue({
    el: '#app',
    data: {
        hours: 0,
        minutes: 0,
        seconds: 0,
        counter: 0,
        my_timer :0
    },
    methods: {
        timer() {
                this.my_timer = setInterval(() => {
                    this.seconds = this.formatTimer(++this.counter % 60)
                    this.minutes = this.formatTimer(parseInt(this.counter / 60, 10) % 60)
                    this.hours = this.formatTimer(parseInt(this.counter / 3600, 10))
                }, 1000);
            },
            pauseTimer() {
                clearInterval(this.my_timer)
            },
            formatTimer(timer) {
                return timer > 9 ? timer : '0' + timer;
            }
    }
})

I hope this explanation is useful.

new Vue({
  el: '#app',
  data: {
    hours: 0,
    minutes: 0,
    seconds: 0,
    counter: 0,
    my_timer:0
  },
  methods: {
    timer() {
      this.my_timer = setInterval(() => {
                                  this.seconds = this.formatTimer(++this.counter % 60)
      this.minutes = this.formatTimer(parseInt(this.counter / 60, 10) % 60)
      this.hours = this.formatTimer(parseInt(this.counter / 3600, 10))
    }, 1000);
  },
  resetTimer() {
    clearInterval(this.my_timer)
    this.hour=0
    this.minutes=0
    this.seconds=0
    this.counter=0
  },
  formatTimer(timer) {
    return timer > 9 ? timer : '0' + timer;
  }
}
        })
<script src="https://unpkg.com/vue/dist/vue.js"></script>
<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <title>Lean Vue</title>
  </head>
  <body>
    <div id="app">
      <p>{{ hours }} : {{ minutes }} : {{ seconds }}</p>
      <button @click="timer">Start</button>
      <button @click="resetTimer">Reset</button>
    </div>

    <script src="dist/bundle.js"></script>
  </body>
</html>

Answer №2

The reason is that this.timer() is resulting in a return value of undefined.

You can make the following adjustments:

timer() {
        this.interval = setInterval(() => {
            this.seconds = this.timerFormat(++this.counter % 60)
            this.minutes = this.timerFormat(parseInt(this.counter / 60, 10) % 60)
            this.hours = this.timerFormat(parseInt(this.counter / 3600, 10))
        }, 1000);
}

Also, include the following code:

pauseTimer() {
    clearInterval(this.interval)
 }

Answer №3

To reset the timer and start counting again from zero, simply manually set the values like this:

this.hours = 0;
this.minutes = 0;
this.seconds = 0;
this.counter = 0;

There is no need to use clearInterval in this scenario.

Keep in mind that setInterval and clearInterval do not impact your custom "counter" variable, so you have to manage it separately.

If you wish to PAUSE the timer:

clearInterval(this.timer())

This will trigger the timer() method once more.

If your intention was to store the returned value and then utilize it to clear the interval, follow this approach:

    timer() {
        this.intervalTimer = setInterval(() => {
            this.seconds = this.timerFormat(++this.counter % 60)
            this.minutes = this.timerFormat(parseInt(this.counter / 60, 10) % 60)
            this.hours = this.timerFormat(parseInt(this.counter / 3600, 10))
        }, 1000);
    },
    pauseTimer() {
        clearInterval(this.intervalTimer)
    },

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

What is the best way to add an index to a v-model in Vue.js?

Currently, I am working on a for loop where I need to attach the index to the value/v-model of the ion-input <div v-for="n in names" :key="n"> <ion-item> <ion-label>Name {{n}}</ion-label> ...

In Internet Explorer 11, React 15.4.1 does not support using objects as valid child components

When trying to render a collection of children in React, make sure to use an array instead of objects. If you encounter the error "Objects are not valid as a React child," consider wrapping the object using createFragment(object) from the React add-ons. Do ...

Tips for capturing an iframe image underneath an HTML5 canvas

I'm attempting to display a webpage on my canvas so that I can make drawings or add notes to it. My goal is to capture a screenshot where the drawing is saved along with the webpage as the background. I tried embedding a URL in an iframe behind the c ...

[Vue alert]: template option is not valid:

I am currently utilizing vue router to load various components. The Home and About components are loading perfectly fine in the browser, however, I am encountering an issue with the Login component which fails to load and results in the error displayed abo ...

Safari is encountering an issue with the value provided for the width/height attribute in the <svg> element, as it is not a recognized

When adjusting the size of an SVG based on antd breakpoints, I encountered errors like these. I am passing props to an SVG element: const { lg } = useBreakpoint(); const height= lg ? "8rem" : xs ? "3rem" : "5rem"; const width ...

Attempting to add an image in an Android WebView

Recently, I have been exploring the most straightforward method to insert an image into a webview using javascript. After crafting my own html and designing a function similar to the one below: <script type="text/javascript"> function image(src) { ...

Having trouble getting Vue to properly focus on an input field

I am attempting to use this.$refs.cInput.focus() (cInput being a ref) but it seems to not be functioning as expected. I expect that when I press the 'g' key, the input field should appear and the cursor should immediately focus on it, allowing me ...

Creating a comprehensive dataset before initiating an AJAX request using jQuery

I've developed a system that enables an admin to assign managers to a campaign through a table. Here's how the table is structured: <tr> <td>Checkbox</td> <td>Last name, First name</td> <td>Employee Id #</td ...

a guide on sending api data as a prop in Vue.js

My current task involves retrieving data from an API and passing it as a prop to a child component. In the parent component, I have the following code: <template> <div class="dashboard"> <items name="Admins" ...

Difficulty encountered when transferring data to child component through props in VueJS

As a beginner in Vue Js, I am currently encountering an issue with my project. I am utilizing Axios to retrieve user data from the JSON placeholder API. This data is being fetched in the Sidebar component through Vuex getters. Within the Sidebar component, ...

obtain or retrieve a data file from the server

I am working with JSON data received from the backend in a specific format. { id: 2 name: dream file file : /home/bakcend/go/uploads/173ba017f27b69b42d7e747.png //backend path } Currently, files uploaded from the front end are stored in a separate dir ...

The server cannot be started by Npm, the complete log is available. However, this project has the ability to operate on a different computer

I am facing an issue with a Vue NodeJs project that I copied from another computer. While it runs smoothly on the original computer, I am encountering difficulties running it on this one. Although I have installed Node.js here, the project fails to run as ...

When running a callback function, the "this" of an Angular 2 component becomes undefined

One issue I'm facing is with a component that fetches data from a RESTful endpoint using a service, which requires a callback function to be executed after fetching the data. The problem arises when attempting to use the callback function to append t ...

Having issues with the delete button when trying to filter data in a list?

Currently, I am working on a list where users can add items with two options: Delete the whole list Delete a specific item. However, it seems that the "handeDelete" button is not functioning properly. Could someone please point out what mistake I made in ...

Filling a martial arts training center's drop-down menu with choices using an Ajax response message

Within my application, there are two drop down menus. The first drop down menu allows users to select the type of institution, and I have added an onchange event that triggers a JavaScript function to make an AJAX call in order to populate the second drop ...

Utilizing JavaScript to access and parse an XML file within a client-side environment

I've recently started learning JavaScript and I'm facing some challenges while trying to reference an xml file uploaded by a user. My goal is to eventually parse the XML contents, update them, and allow users to download the modified file. Here ...

What is the maximum level of referencing allowed in v-if conditions?

I'm encountering an issue with some markup I have: <div class="form-group" v-if="model.owner.enabled"> The model object in the scope is structured like this: { ... owner: { enabled: true ... } ... } However, Vue is th ...

The ID Token could not be verified due to an invalid jwt.split function

I'm currently working on validating a Google ID Token on my Node.js server. Unfortunately, I've encountered the following error: The ID Token cannot be verified: jwt.split is not a function For reference, here is the link to the code that I am ...

What is the process for pulling out a specific JSON element based on a condition?

I am working with a JSON object that looks like this: "links" : [ { "rel" : "first", "href" : "http://localhost:8080/first" }, { "rel" : "self", "href" : "http://localhost:8080/self" }, { "rel" : "next", "href" : "http://loca ...

Check if the input values are already in the array and if not, then add

Within my React application, I am displaying an Array and each entry in the Array is accompanied by an input element. These input elements are assigned a name based on the entry's ID, allowing users to enter values. To handle the changes in these inp ...