Vue: setInterval not updating timer variable

Here is my code for updating and displaying the number of elapsed seconds:

<template>
 
 <div>
   {{timerValue}}
   
 </div>
 
  </template>

<script>
 export default {
  name: "App",
  components: {
     
  },

  data() {
    return {
      timerValue: ""
    }
  },

  created()  {
     let seconds = 0;
      this.timerValue = seconds;
      setInterval(function()  {
           seconds++;
      })
  }
};
</script>

Despite my efforts, the page always displays

0

I'm not sure what I am doing wrong. Can someone help me figure it out?

https://codesandbox.io/s/still-cache-1mdgr6?file=/src/App.vue

Answer №1

If you're looking for a solution, perhaps the code snippet below can help:

const app = Vue.createApp({
  data() {
    return {
      timerValue: 0 // default value is set to 0 
    }
  },
  created()  {
      setInterval(() => {
           this.timerValue++;
      }, 1000)
  }
})
app.mount('#demo')
<script src="https://unpkg.com/vue@3/dist/vue.global.prod.js"></script>
<div id="demo">
  <div>
    {{timerValue}}
  </div>
</div>

Answer №2

Instead of incrementing seconds, make sure to increase this.timerValue within the code.

created() {
     let seconds = 0;
      this.timerValue = seconds;
      setInterval(function() {
           this.timerValue++;
      }.bind(this))
  }

You can also achieve the same result using arrow functions:

created() {
     let seconds = 0;
      this.timerValue = seconds;
      setInterval(() => {
           this.timerValue++;
      })
  }

Answer №3

Here are three important points to keep in mind:

  • In the setInterval function, only the seconds variable is being updated, not this.timerValue. This results in the page always displaying 0.
  • The setInterval function does not have an interval argument specified, so it will not run every second as intended.
  • The initialization value is unclear, take some time to understand the program logic and review what you have written.
<template>
 
 <div>
   {{timerValue}}
 </div>
 
 </template>

<script>
 export default {
  name: "App",
  components: {
     
  },

  data() {
    return {
      timerValue: 0,
    }
  },

  mounted()  { // using mounted is better than created in this scenario
      setInterval(() => {
           this.timerValue++;
      }, 1000)
  }
};
</script>

References: https://www.w3schools.com/jsref/met_win_setinterval.asp

Answer №4

If you want to dive into something new, I always recommend starting with language logic or at least JavaScript.

It's important to update the React value because JavaScript doesn't have an API that allows memory cell assignment.

<script>
 export default {
  name: "App",
  components: {
     
  },

  data() {
    return {
      timerValue: 0 // initial value is set as a number
    }
  },

  created()  {
      setInterval(() => {
           this.timerValue++;
      }, 1_000 /* delay of 1 second */)
  }
};
</script>

Answer №5

I discovered two issues with my code:

  1. Using this within a function(). It is preferable to use an arrow function, like so:
setInterval(() => {}
  1. this.timerValue = seconds alone does not prompt Vue to update timerValue when seconds changes. Modifying seconds does not automatically update timerValue.

This can be addressed by utilizing a computed property:

computed:  {
  timerValue: function()  {
    return this.seconds;
  }
},

The revised code would resemble the following:

https://codesandbox.io/s/festive-cannon-8qvpn9?file=/src/App.vue

<template>
  <div>
    {{ timerValue }}
  </div>
</template>

<script>
export default {
  name: "App",
  components: {},

  data() {
    return {
      seconds: 0,
    };
  },

  created() {
    setInterval(() => {
      this.seconds++;
    }, 1000);
  },

  computed: {
    timerValue: function () {
      return this.seconds;
    },
  },
};
</script>

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

Tips for properly formatting functional Vue components?

Below is a functional component that functions as intended. <template functional> <div> <input /> </div> </template> <script> export default { name: "FunctionalComponent" } </script> <styl ...

Vue Eslint Extension

My current project utilizes the eslint vue plugin with specific rules set in place. "rules": { "vue/html-closing-bracket-newline": ["error", { "singleline": "never", "multiline": "always" }], "vue/html-closi ...

What could be the reason for PassportJS in Node failing to clear the session upon logout?

I am encountering an issue with my system not successfully logging out using PassportJS. The logout route appears to be triggered, but the session is not being removed as intended. I would like it to return a 401 error if the user is not logged in on a spe ...

Completed Animation with Callback in AngularJS CSS

Currently working with AngularJS and hoping to receive a notification upon completion of an animation. I am aware that this can be achieved with javascript animations such as myApp.animation(...), but I'm intrigued if there is an alternative method wi ...

The loading of the module from was hindered due to an invalid MIME type restriction

Exploring a three.js example and encountering an issue when utilizing import within a JavaScript module. The error message displayed is: Loading module from “http://localhost:8000/build/three.module.js” was blocked because of a disallowed MIME type ( ...

The button fails to function properly following the initial successful loading of ajax data

var Update = { init: function(){ $('.find').on('click', function(e){ e.preventDefault(); var $this = $(this), $form = $('#searchForm'); BLC.ajax({ ...

Verify if the user is already present in the MongoDB database and authenticated with Passport

I'm currently exploring the usage of passport and I am in the process of setting up a "register" page functionality. The registration process is working smoothly, along with the log-in form. Yet, I am looking to implement a validation to check if the ...

Transitioning from Vuetify 2 to Vuetify 3: Handling v-list-item-icon with v-if Conditionals

I have streamlined this post to focus solely on v-list-item-icon; if that's what you're here for, scroll down for the answer. A commenter suggested splitting my migration questions into separate posts. I've followed that advice and created ...

"Exploring the Power of Angular Change Detection with Promises in a Hybrid

We are currently in the process of upgrading an AngularJS project to Angular 7 by following the recommended "hybrid" approach where both frameworks coexist. However, we have encountered some issues with change detection when dealing with native promises. T ...

Update the JSON by replacing any null values with a predefined string

When working with JSON data, I often come across empty values that I need to replace with a default string. var jsonData= [ { "machineNum": "1A", "serialNo": "123", "city": "" }, { "machineNum": "2B", "serialNo": "", "city": "" }, ...

How can we accurately identify the server that initiated an AJAX call in a secure manner?

Imagine a scenario where Site A embeds a JavaScript file from Server B and then makes a JSONP or AJAX request to a resource on Server B. Is there any foolproof way for Server B to determine that the specific JSONP request originated from a user on Site A, ...

What categories do input events fall into within Vue?

What Typescript types should be used for input events in Vue to avoid missing target value, key, or files properties when using Event? For example: <input @input="(e: MISSING_TYPE) => {}" /> <input @keypress="(e: MISSING_TYPE) = ...

Sharing data between Test1 and Test2 components in Vue.js

I need to transfer the value of total:120 from my Test1.vue component to Test2.vue. Can anyone guide me on how to achieve this? Test1.vue: <Test2 v-bind:totalPrice='totalValue'></Test2> data() { return { t ...

Can anyone recommend an easy regular expression to validate date format patterns?

While searching for regex patterns to validate date values in a specific format, I came across numerous options. However, I prefer to allow users to input their own custom date patterns such as: d-mm-yyyy MM/dd/yy yyyy.mm.d I am looking for a ...

Unity3D: Troubleshooting a Code Issue

Encountering an issue with my code and struggling to find a solution. I've tried moving my c# script up to the standard assets folder as suggested in my research but it didn't resolve the problem. Any assistance would be greatly appreciated! Than ...

Backand - How can I display the contents of variables using console.log() within Security Actions?

Is there a way to utilize console.log() in Backand, specifically within the server side functions like those found under Security & Auth > Security Actions? I have checked the Read.me which suggests using 'console.log(object) and console.error(obje ...

Utilizing Google App Engine for seamless deployment, integrating Ajax for dynamic interactions, and

Using the google App Engine, I am looking to implement javascript (or Ajax) for POSTing a form and updating the target div. The form includes multiple fields and files for transfer. The javascript function I am using is extracted from the "Javascript: The ...

What is the proper jQuery traversal method to display a single templated element?

Utilizing handlebars as the view engine for node.js, the subsequent html content is dynamically produced and repeated: http://jsfiddle.net/4Q5PE/ <div class="btnsContainer"> <div class="btn-group" data-toggle="buttons"> <label cla ...

Error message: Iframe chrome encountered a Uncaught DOMException when attempting to access the 'localStorage' property from 'Window': Document does not have permission

I recently developed a JavaScript widget that utilizes localstorage to set and retrieve properties of the window. Upon opening this widget in Chrome, I encountered an error message: Uncaught DOMException: Failed to read the 'localStorage' prop ...

The issue with the trigger function in jQuery is specifically affecting Chrome browser

When attempting to load a modal window using a link like , I am encountering issues in Chrome, Safari, and IE. However, Opera and FF are functioning properly. The modal window is being called as an iframe. Other buttons that are supposed to open the modal ...