Vue.js Timer Tracker

I am attempting to create a countdown timer in Vue.js that displays the remaining time.

new Vue({
    el: "#app",
    data: {
        timer: 25,
        message2: "",
        counter: false,
        interval: null
    },
    methods: {
        startTimer() {
            this.interval = setInterval(this.countDown(), 1000);
        },
        countDown() {
            if (this.counter === false) {
                var n = this.timer;
                this.counter = true;
            } else if (n > 0) {
                n -= 1;
                this.message2 = "You have " + n + "seconds left.";
            } else {
                clearInterval(this.interval);
                this.counter = false;
                this.message2 = "Your time is up!"
            }
        },

However, I am encountering an issue where the message2 does not update with each tick of the Interval when the countDown() function is called. Instead, it only runs once after the initial execution.

Answer №1

In order to correctly use setInterval, make sure to pass the function itself rather than its result:

startTimer() {
  this.interval = setInterval(this.countDown, 1000);
}

Furthermore, there are some errors in the countdown() function that need attention (such as mistakenly defining n within an if statement and using it outside of that block, leading to undefined behavior). Additionally, be cautious when modifying local variables without affecting the intended target variable this.timer.

countDown() {
  var n = this.timer;
  if (!this.counter) {
    this.counter = true;
  } else if (n > 0) {
    n = n - 1;
    this.timer = n;
    this.message2 = "You have " + n + " seconds left.";
  } else {
    clearInterval(this.interval);
    this.counter = false;
    this.message2 = "Your time is up!";
  }
}

Answer №2

It has been mentioned by others that passing your function to setInterval is the correct approach, rather than invoking it and passing its return value.

In addition, when you run the line n = this.timer, you are essentially calling the getter set up by Vue on this.timer, and assigning the number 25 to your variable n. However, since n goes out of scope once the function completes, your copy of 25 is lost. Consequently, in the next iteration of your function (one second later), n is undefined. This leads to the else clause clearing the interval, causing the elseif clause to never be executed.

To ensure your code functions correctly, I suggest a minor modification: include n: undefined, in your data:{} so that it can be monitored by Vue. Subsequently, replace all instances of n with this.n.

Once you have resolved that issue, here are some simplifications you might consider:

  • Moving this.n = this.timer assignment inside startTimer
  • If you assign this.interval = undefined when clearing the interval, this.counter becomes unnecessary as you can just verify if this.interval exists
  • Transforming message2 into a "computed" property
  • Adding an if statement within startTimer to prevent adding a second interval if one is already active (e.g. preventing multiple clicks on a "start timer" button before the initial timer finishes)

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

Refreshing component after changing state in vue.js

I have been troubleshooting an issue with NuxtJS and VueJS where a component fails to re-render after a state change. Here is the index.js file: Vue.use(Vuex) const state = { productsHome: [], accessToken: {}, collections: {}, product: {}, car ...

Applying autocomplete (Jquery) functionality to dynamically loaded partial views using AJAX in MVC4

I have a situation where I need to create Project models with a table of company-related data. To achieve this, I have implemented a button that triggers an AJAX call to fetch a partial view and add it to the table: $("#addCompanyRoleProject").click(funct ...

Sending information from one page to another and then sending it once more

I am currently utilizing the following code to submit a form's data to : <script type="text/javascript"> $(document).ready(function(){ $("#textnextofkin").validate({ debug: false, rules: { ...

The jQuery click and load function are failing to function as expected

Currently, I am facing an issue while trying to load text from a txt document into a div using the following code: $(document).ready(function(){ $('button').click(function(){ $('#contenthere').load('Load.txt'); ...

Matching two arrays and performing an operation on them

Is there a way to search for a specific value in an array and if it exists, then add another value into a different array? I have two large arrays: one containing people and the other containing blogs. I want to accomplish this using JavaScript. Here is a ...

Guide to extracting additional data from a JSON array upon selection of a value within an option tag using jQuery

Seeking assistance to enhance the display of museum information when a museum name is selected from an option dropdown box. The data is extracted from a json array. Although I managed to populate the option box with the museum names, I am encountering di ...

Implement a loading spinner to display each time a computed method is invoked in a Vue.js

Whenever a checkbox is checked, my filtering method gets triggered. I am trying to implement a loader that displays while the filter process is ongoing and then shows the results. However, I have encountered an issue where the loader remains visible at all ...

Working with content that includes Laravel Blade code in Vue.js

#SeekingHelp I need assistance with an issue I'm facing. My blog content includes syntax examples like {{ $title }} as it describes Laravel Blade. The Issue: When rendering my blog content on Vue.js, everything goes haywire due to the Blade syntax { ...

Combining arrays and encoding in Json格式

I have a process that generates multiple arrays in PHP: for ($t=0;$t<2;$t++) { for ($xx=0;$xx<$totf[$t];$xx++) { $otdata[$t][$xx] = array("".$otname[$t][$xx]."" => ['games'=> $otg[$t][$xx], 'mint'=> ...

When it comes to Redux, is it considered an anti-pattern to pass an event from a presentational component to a container component

As a newcomer to Redux, I am challenging myself to rebuild an old React app using this technology in order to gain proficiency. However, I am facing a significant challenge regarding where to place the logic within the application. My understanding is tha ...

Error: Unable to locate sportsRecord due to missing function

updated answer1: Greetings, I have updated the question with some detailed records and console logs for better understanding. sportsRecord = { playerTigers:[ {TigerNo: 237, TigerName: "Bird Bay Area", TigerkGroupNo: 1, isDefault: true ...

Exploring the Safari browser with Polymer 2.0

Looking for some help with a question I have... I've been experimenting with the new Polymer 2.0 preview on Safari, but it doesn't seem to be working correctly. I'm using a simple code (just my-element) in the index.htm file, loading the pol ...

Dynamic Bootstrap Tab menu slider with movable functionality when the limit is reached

I am facing an issue with the tabs menu on my website. The tabs menu items can vary between 2 or 3 to even 20 or more. When the number of navigation items exceeds 10, they automatically drop to the second line, which you can see here. However, I don' ...

Ways to perform a redirect following data retrieval from a post request

I am working on a post method for a servlet, where the servlet returns a web page after forwarding a request to another page. Instead of directly redirecting using window.location = "/AnotherServlet", I have tried various solutions including passing parame ...

Differences between JavaScript's window.onload and body.onload functionsWhen

My inquiry is similar yet slightly distinct from the one queried here: window.onload vs <body onload=""/> The comparison in that prior query was between utilizing window.onload and inline js. My question pertains to the disparity between ...

The latest on rectAreaLight enhancements in three.js

It seems like this abandoned feature of three.js has become somewhat of a coveted prize; I've attempted to incorporate it a few times without success. You can find an example that works on an older release here: My minimal broken example is availabl ...

The Material UI dialog is causing issues for CKEditor 4

In the midst of my React project, I have incorporated CKEditor 4 into a Material UI dialog. However, when attempting to utilize advanced features like Math, I encounter an issue where I am unable to input any text into input or textarea fields. Despite sea ...

What is the best method to access nested objects in react-native when working with this.state?

I am working with a straightforward component, shown below: import React, { Component } from 'react'; import { StyleSheet, Text, View } from 'react-native'; export default class Statistics extends Component { constructor(p ...

Encountering AngularJS promise data parsing issues

I am trying to work with promises in AngularJS. However, I encountered an error while parsing the backend response in AngularJS. What could be the issue here? This is the HTML code: <div ng-app="clinang" ng-controller="pacientesCtrl"> <a ...

Issue encountered with Ionic and ssh2: process.binding is not supported

I am currently delving into the world of Ionic and experimenting with creating a basic application that utilizes SSH2 to establish an ssh connection between the app and a server. Here is a breakdown of the steps I took to encounter the issue: Steps to Rep ...