Why is my timer function speeding past too swiftly?

My vue.js countdown function is updating too quickly.

Displayed below is the data section

data() {
        return {
            selected: [],
            countdown: timerLimit
        }

Here is the countdown method

countdownTimer() {
        this.countdown = 60;
            var downloadTimer = setInterval(() => {
            if(this.countdown <= 0){
                clearInterval(downloadTimer);
                if (this.thisUser.captain) {
                        Store.submitTurnEnd();
                    }
            }
            this.countdown -= 1
            console.log(this.countdown)
            }, 1000);
        },

I have noticed that after a few clicks, the countdown function speeds up. I believe I need to modify the data section, but I am uncertain of the correct approach.

Thank you for your assistance.

Answer №1

Perhaps including another variable in your data can be beneficial:

data() {
        return {
            selected: [],
            countdown: timerLimit,
            isCountdownActive: false
}

Here is the method:

countdownTimer() {
        // Check if the countdown is already active
        if(this.isCountdownActive == true) return;

        // Activate the countdown for the first time
        this.isCountdownActive = true

        this.countdown = 60;
            var downloadTimer = setInterval(() => {
            if(this.countdown <= 0){
                clearInterval(downloadTimer);
                if (this.thisUser.captain) {
                        Store.submitTurnEnd();
                }

                // Reset countdown activity to false upon completion
                this.isCountdownActive = false
            }
            this.countdown -= 1
            console.log(this.countdown)
            }, 1000);
},

Answer №2

Feel free to give this a shot!

const myVueApp = new Vue({
  el: "#app",
  data: {
    counter: 5
  },
  methods: {
    startCountdown: function() {
        let interval;

        interval = setInterval(() => {
            if (this.counter > 0) {
                this.counter = this.counter - 1;
            } else {
                clearInterval(interval);
                // Add your custom logic here
            }
        }, 1000);
    }
  }
})

Here is the corresponding template section:

<div id="app">
  <h2>Countdown:</h2>
  <h1>{{ counter }}</h1>
  <button v-on:click="startCountdown">Begin</button>
</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

The transition in Vue Js is only effective when elements are entering, not when they are

Attempting to implement a vue js transition from bottom to top and top to bottom. The transition works smoothly from bottom to top when entering, but there is no transition effect when leaving. Below is the CSS code for the transition: .slide-details-mob ...

Discovering the method to retrieve files from the public folder via URL in next.js

I am working on a Next.js project where users have the ability to upload images. These images are stored in the public directory. Is there a way for me to access these files using a URL structure like mydomain.com/public/coverimg/image.jpg? Below is my AP ...

Creating a carousel of cards using JavaScript, CSS, and HTML

Here is a visual reference of what I'm attempting to achieve: https://i.stack.imgur.com/EoQYV.png I've been working on creating a carousel with cards, but I'm struggling to synchronize the button indicators with card advancement when clicke ...

Ensure you have the correct loader specified for Laravel Mix

After compiling my assets import './bootstrap'; import './components'; const app = new Vue({ el: '#app' }); This is the content of my package.json file: { "private": true, "scripts": { "dev": "node node_module ...

The dynamically generated hyperlink is not displaying correctly

I've been attempting to display a link on my page, but instead of returning the /register path, it immediately redirects to the UTMs.... The href displayed on the site is domain.com/?utm_campaign... rather than domain.com/register?utm_campaign... ...

Is there a specific code repository available that can verify and transform blog comments into XHTML strict format?

I'm currently developing a PHP website that allows users to make comments similar to a blog, and I am specifically interested in restricting the use of certain HTML tags. Is there any existing library that can process user comments and output valid XH ...

Interested in generating buttons automatically based on a JSON file

Currently, I am faced with the challenge of creating buttons within a CSS grid without knowing the exact number of buttons that will be populated from a JSON file. The range could vary greatly, from as few as 5 to as many as 55. I am seeking guidance on t ...

Guide on executing protractor suites with various users

I have a config file that I usually use to execute a single user and multiple test suites. However, I am currently facing an issue where I need to run certain protractor suites with User A and other protractor test suites with User B. I am unsure of how to ...

Unlocking the Secret Code

Presenting the question: checkPassword([["Peter", "P"], ["Sarah", "S"], ["Ethan", "R"]], {"Peter": "P", "Sarah": "Q", //"Ethan":"E"}) ...

Challenge encountered while implementing a countdown using a for loop in a node.js application

I've been struggling with the following code and despite trying everything, I can't seem to find a solution. Hopefully, someone out there can lend me a hand. Currently, the code runs fRoll.roll, enters a FOR loop, initiates the countdown of the ...

Utilizing Vue 3's Inject Plugin alongside the powerful Composition API and TypeScript

I developed a controller plugin to be used globally in all components, but I am facing challenges making it compatible with Vue 3 + TypeScript + Composition API as I keep getting a TypeScript error. ui/plugins/controllers.ts import { App } from 'vue& ...

The body-parser module in express 4.0 is currently not accessible for the route handler

I am attempting to send a PUT request via Google Postman in the following format: PUT /updateUser/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="debcbcbc9eadadadf0bdb1b3">[email protected]</a> HTTP/1.1 Host: loca ...

Updating NavBar text dynamically based on user login status in React.JS

Within my project, there is a Navigation bar that I access from App.js. Depending on whether I am logged in or not, I want to display different versions of the NavBar. When logged in, the NavBar should have a logout button. And when logged out, it should s ...

npm: Generating debug and production builds while ensuring accurate dependency management

I am in the process of developing a single page application using TypeScript along with various other dependencies such as jQuery, immutable, lodash, and React. Each resulting module is integrated into the project using requirejs. My goal is to generate t ...

Getting rid of excess white space in ajax search

Recently, I developed an ajax search box that uses the keyup function to search for profiles in my database. $('#asearch').keyup(function(){ var search_term = $(this).val(); However, I encountered an issue where once I type a first name int ...

Error: Trying to access the 'previous' property of an undefined value

I keep encountering an error with functions in firebase: TypeError: Cannot read property 'previous' of undefined at exports.sendNotifications.functions.database.ref.onWrite (/srv/index.js:5:19) at cloudFunction (/srv/node_modules/firebase-functi ...

Combining CodeIgniter4 with Vue.js and Webpack's devServer to handle CORS issues

Exploring Vue & CodeIgniter 4, starting from https://github.com/flavea/ci4-vue. No matter what I try, I encounter a persistent CORS error in dev mode: Access to XMLHttpRequest at 'http://example.com/public/api/book/get' from origin &apo ...

sinon: Techniques for stubbing an entire class as opposed to singular methods

I am faced with a situation where I have a class that instantiates another class in my test. My goal is to stub out the entire second class, ensuring that its constructor is never invoked. Consider the following scenario: Test.js class Test { construct ...

Creating a React.js component and setting an initial value within it

Recently delved into the world of React.js and currently attempting to create a reusable header that can switch between two states: one for when the user is logged in, and another for when the user is not logged in. // Header.js var Header = React.createC ...

Expanding circle with CSS borders on all edges

My goal is to create a background reveal effect using JavaScript by increasing the percentage. The effect should start from the center and expand outwards in all directions. Issue: The percentage increase currently affects only the bottom and not the top ...