Timed up 10-second countdown with vue.js

<html>
<head>
  <meta charset="utf-8" />
  <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" ></script>
  <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
  <style>
    div#app { padding: 30px; margin: 30px auto; width: 300px; text-align: center;
      border: 1px solid #ccc; box-shadow: 3px 3px 3px #aaa; }
    div#time { font-size: 25pt; padding: 5px; margin: 0px auto; background: #ccc;
      width: 200px; border: 1px solid black; }
  </style>
</head>

I am struggling with a Vue.js timer that should count up to 10 seconds using the moment() method. However, I am facing an issue where the timer does not stop after reaching 10 seconds. I have tried using both a variable 'count' and clearInterval() but without success. Can anyone provide some guidance on how to properly set clearInterval when the timer reaches 10 seconds?

<body>
  <div id="app">
    <h1>counter1</h1>
    <div id="time">{{ time }}</div>
  </div>

<script type="text/javascript">
    var count=0;
    var app = new Vue({
      el: '#app',
      data: {
        time: "0",
        count:0
      },
      mounted() {
          this.startTime = moment();
          let callback = () => {
            let time_diff = moment().diff(this.startTime);
            this.time = moment.utc(time_diff).format("s");
            this.running=true;
            

            
          };
        let interval= () =>{ setInterval(callback, 1000);
            ++count;
            if(count==10) clearInterval(interval);
        }

          interval();
         
        }
    })
   </script>

Answer №1

You have defined the interval in this manner:

let interval = () => { setInterval(callback, 1000);

The interval function wraps around the setInterval. To stop the interval, you should store the result value outside of a nested function.

After removing the function, here is an example of a working demo:

var count=0;
var app = new Vue({
    el: '#app',
    data: {
        time: "0",
        count:0
    },
    mounted() {

        // Create startTime
        this.startTime = moment();

        // Define callback
        let callback = () => {

            // Calculate time difference
            let timeDiff = moment().diff(this.startTime);
            this.time = moment.utc(timeDiff).format("s");
            this.running=true;

            // Increase counter
            ++count;

            // Stop interval when count reaches 10
            if (count == 10) clearInterval(interval);
        };

        // Start the interval
        let interval = setInterval(callback, 1000);
    }
})
div#app  { padding: 30px; margin: 30px auto; width: 300px; text-align: center; border: 1px solid #ccc; box-shadow: 3px 3px 3px #aaa; }
div#time { font-size: 25pt; padding: 5px; margin: 0px auto; background: #ccc; width: 200px; border: 1px solid black; }

/* Hide console wrapper */
.as-console-wrapper { display: none !important; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment-with-locales.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>

<div id="app">
  <h1>counter1</h1>
  <div id="time">{{ time }}</div>
</div>

Answer №2

To appropriately handle the interval ID given by setInterval, it's crucial to clear it when necessary as demonstrated below:

<script type="text/javascript">
    var count=0;
    var app = new Vue({
      el: '#app',
      data: {
        time: "0",
        count:0
      },
      mounted() {
          this.startTime = moment();

          let interval;
          let callback = () => {
            let time_diff = moment().diff(this.startTime);
            this.time = moment.utc(time_diff).format("s");
            this.running=true;

            ++count;
            if(count == 10) clearInterval(interval);            
          };

          interval = setInterval(callback, 1000)
    })
</script>

For further details, refer to WindowOrWorkerGlobalScope.setInterval().

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

Persistent vertical menu dropdown that remains expanded on sub menu pages

I am struggling to understand how to keep my menu sub items open when on the active page. Although I have tried similar solutions, I have not been successful in implementing them. I apologize if this question has been asked before. My approach involves usi ...

Adding a CSP nonce to inline styles and scripts injected by Vue can be achieved in a Laravel and Vue project with Vite

In my repository, I have a combined Laravel and Vue project utilizing Vite. CSP has been integrated using spatie/laravel-csp, with successful generation of the header nonce for script-src and style-src when inspected in the browser. However, I am encounte ...

When Socket.emit is called, it outputs <span> elements within a well-structured message

Currently working on a small chat application using Node.js, Express.js, and Socket.IO. However, I'm encountering an issue with formatting. Instead of displaying the message content within <span> tags as intended, it is printing out the actual t ...

What are the benefits of using beforeRouteEnter over mounted in Vue.js?

What is the purpose of the beforeRouteEnter navigation guard in vue-router? Can you give examples of times when beforeRouteEnter may be triggered without mounted being called? When would you choose to use beforeRouteEnter over mounted? ...

An illustration of Vue.js paginator HTML structure

I have a question regarding the implementation of vuejs-paginator and I'm struggling to get it working with my backend setup. Here's what I have in mind: <script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.10/vue.js"></script&g ...

Using Vuex: Delay dispatch of action until websocket response received

Let's look at the given scenario and premises: To populate a chat queue in real time, it is necessary to establish a connection to a websocket, send a message, and then store the data in a websocket store. This store will handle all the websocket sta ...

Observables waiting inside one another

I've encountered an issue where I need to return an observable and at times, within that observable, I require a value from another observable. To simplify my problem, let's consider the following code snippet: public dummyStream(): Observabl ...

Convert an array of string values into a JSON format

I need help with converting an array stored in my database to a more user-friendly format. Currently, it is saved as follows: ["size:medium","height:10cm"] This format makes it difficult to display in a table. I am wondering if there is a way to conver ...

Enhancing class names in production mode with Material UI, Webpack, and React to optimize and minimize code size

webpack - v4.5+ material ui - v4.9.7 react - v16.12.1 Ordinarily, all classes should follow the pattern of the last one in the first example. However, for some unknown reason, many classes remain unchanged in production mode. Any thoughts on this issue? ...

Does aoMap function exclusively with THREE.BufferGeometry?

Can you provide guidance on setting up an aoMap for a standard THREE.Geometry object? Is there a demo available to reference? var uvCoordinates = geometry.attributes.uv.array; geometry.addAttribute('uv2', new THREE.BufferAttribute(uvCoordina ...

Encountering a Module not found error with a ValidationError when trying to import an SVG file within a React

I've set up a manual Webpack 5 configuration for my React project with TypeScript. I am facing an issue while trying to import an SVG icon and using Material UI in the project. The error message I'm encountering is: Module not found: ValidationEr ...

Leveraging ng-repeat within ng-view

I am facing an issue with using ng-repeat inside ng-view as the data is not being displayed. I have come across suggestions on forums to use a factory, but I am hesitant to utilize a service because my $scope data relies on $routeParams for querying. var ...

Encountering a problem with Vue when running the node-rdkafka package

I added node-rdkafka to my project using the command npm install node-rdkafka. Then, I included it in my code like this: import Kafka from 'node-rdkafka'; created() { console.log(Kafka.features); } An error occurred when running npm r ...

Create a unique type in Typescript that represents a file name with its corresponding extension

Is there a way for me to specify the type of a filename field in my object? The file name will consist of a string representing the name of the uploaded file along with its extension. For instance: { icon: "my_icon.svg" } I am looking for a ...

The download attribute is not functioning properly on both Chrome and Edge browsers

I've been trying to use the download attribute, but it doesn't seem to be working. I have also attempted to use the target attribute to see if there are any issues with downloading from the server or from a web (https) source. Unfortunately, noth ...

The input field automatically populates with the username that has been stored in the browser's form

Issue: I have created an input field with the type text, but upon page load, it gets automatically filled with a username saved in the browser's form data for this website's login page. I want it to show up clean when the page loads. <input t ...

Extract specific nested elements

Looking for assistance with extracting specific nested objects from a series structured like so: data = {"12345":{"value":{"1":"2","3":"4"}}, {"12346":{"value":{"5":"6","7":"8"}}, {"12347":{"value":{"9":"0","11":"22"}} In need of creating a functio ...

`How can I define dependencies and build an npm package?`

I have authored several npm modules, all of which are designed to enhance existing libraries such as three.js or react. While the packages appear to be downloaded, I have not received any feedback confirming whether they have been implemented correctly. ...

Data vanishing in upcoming authentication session in test environment

I have encountered an issue with next auth in my next.js project. During development, the session data is lost if the server refreshes or if I switch to another tab and return to it. This forces me to sign out and then sign back in to restore the session d ...

Error encountered when attempting to integrate FontAwesome into the body of a Next.js Link

I'm currently using the react-fontawesome library in my project built with Next.js. However, I've encountered an issue when trying to include an icon inside the Link component. The error message is confusing and I can't seem to figure out wh ...