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

Compile a selection of messages from the conversations into an array

Need assistance in displaying messages from a chat Id using Vue js. I have managed to retrieve the data but facing issues in displaying them using the component. Any guidance would be much appreciated. This is where the messages will be displayed: <tem ...

Need a jQuery function that updates the 'id' after clicking on a specific div? Here's how to do it!

I need help simplifying my current situation. Step 1: I want to increment the variable "count" by 1 every time a specific div is clicked. Step 2: After updating "count", I want to utilize it in another function. This function involves copying the value f ...

Tips for navigating through pagination indexes with Angular 6

Hey there, I'm currently working on a project where I need to automatically click through each pagination index. Initially, only the first index can be clicked. After that, the following page indexes are not clickable. Here's the code snippet: ...

Learn the process of extracting an array of objects by utilizing an interface

Working with an array of objects containing a large amount of data can be challenging. Here's an example dataset with multiple key-value pairs: [{ "id": 1, "name":"name1", age: 11, "skl": {"name": & ...

What is the best way to implement a switch case for the value of a property within an object in a TypeScript file?

The object I'm dealing with looks like this: {a: auth?.type === '1' || auth?.type === '2' || auth?.type === '3' ? { reason: // I need to implement a switch case here : un ...

Why is it that when accessing the property of an object within a computed object, it returns as undefined instead of the object itself? Which method would be more suitable in this

Salutations. To provide some context, my intention in posing this query is to dynamically render a child component within a form based on the selection made using the <app-selector> Vue component, as straightforward as that. To simplify matters, I ...

Create two unique jQuery click events for the same element

I am working on a website where I have implemented a button that uses jQuery to change the CSS of certain elements when clicked. Now, I am looking for a way to assign another function to revert the CSS changes back to their original state when the button ...

Ways to adjust your selection to the space or new line before or after

$('button').on('click', function(){ const selection = window.getSelection(); selection?.modify('move', 'backward', 'word'); selection?.modify('extend', 'forward', 'to the next space ...

ng-class: Issue detected - The symbol '-' is positioned at column {2}

I'm having an issue with ng-class. I need to add a disabled state class if the role has admin privileges, but I keep getting an error. Here is the HTML: <label class="toggle modal-label-box" ng-class="{state-disabled: checkCanModify()}"> &l ...

What is the method for configuring Express to serve static files from a parent directory?

If I have a nodejs express application with the following folder structure: -app - frontend - assets - images - scripts - styles - ... - pages - backend - server.js How can I serve the static files in the assets fold ...

React throwing error: Context value is undefined

Why is the Context value showing as undefined? The issue lies in src/Context.js: import React, { Component } from 'react'; const Context = React.createContext(); export class Provider extends Component { state = { a: 1, b: 2 }; render( ...

When utilizing JavaScript to input text, I have observed that if I enter text in one text box, any previously entered value is automatically deleted

Currently, I am facing an issue with 3 text boxes in a row that I am populating using JavaScript. The problem arises when I enter text into one field and then move to the second box to input text - the value from the first text box gets removed. Below is ...

Efficiently filtering and organizing data within a table using Vue js

I've recently set up a table and was looking to implement sorting and searching functionalities using vue.js. While attempting to do so, I came across this helpful resource which provided some guidance, but unfortunately, I still haven't been abl ...

ever-evolving background-image with dynamic CSS styling

Being new to both PHP and Javascript, please excuse any mistakes in my explanation. I have information stored in a PHP array that I bring to my index page using the function below (located in a separate file called articles.php that is included in my index ...

Looking to create an anchor tag that navigates to a specific ID on the page while accommodating a fixed header placement

In my application, the homepage's carousel displays multiple images with dynamically generated anchor tags that link to different routes. When clicking on the anchor tag, the page scrolls to the linked image but is obstructed by a fixed header. I want ...

The function of AJAX is to send and receive data asynchronously without

Recently, I was experimenting with AJAX. When I use echo "hello" in my PHP file, everything works perfectly. However, if I try something like echo "<script language=Javascript> alert('hi');</script>"; in the PHP file, the alert ...

moving a simulated element to a new location

Looking for some help with my html/CSS code that creates a unique element at the bottom of a div with an image background. The shape I've created is positioned at the bottom of the div... Below is the HTML: <div style="background-image:url(&apos ...

The eval() function does not run scripts from external sources with a src attribute

Instead of using eval() to execute all <script> tags after completely rewriting a div, I have encountered an issue. The following code snippet works for inline-scripts, but it doesn't have the same effect on external scripts like: <script sr ...

What is preventing me from accessing a function that is declared using function declaration while using a debugger?

When pausing at the debugger statement, an attempt to call foo results in a ReferenceError. It appears that the function is not defined within the script's context or scope, similar to how a local variable like x is. The script example.js is as follo ...

Integrating a fresh element into the carousel structure will automatically generate a new row within Angular

I'm currently working on an Angular4 application that features a carousel displaying products, their names, and prices. At the moment, there are 6 products organized into two rows of 3 each. The carousel includes buttons to navigate left or right to d ...