Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

"now" is not defined when trying to update time

So I am doing a vue.js project and I am trying to have the time update every second. I have initialized the time in data(), then created a function which should update it, and then called the function in mounted() to refresh every second. Problem is that when I call updateTime() it keeps telling me that ‘now’ is not defined. Why is that?

    <script>
import { createDOMCompilerError } from "@vue/compiler-dom";

export default {
  data() {
    const now = new Date();
    const hours = now.getHours();
    const minutes = now.getMinutes();
    const seconds = now.getSeconds();

    return {
      now,
      hours,
      minutes,
      seconds,
    };
  },
  methods: {
    updateTime() {
      this.now = new Date();
      this.hours = now.getHours();
      this.minutes = now.getMinutes();
      this.seconds = now.getSeconds();
    },
  },
  mounted() {
    setInterval(() => {
      this.updateTime();
    }, 1000);
  },
  unmounted() {
    clearInterval();
  },
};
</script>

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

You need to use this.now when assigning to this.hours etc

this.now = new Date();
this.hours = this.now.getHours();
this.minutes = this.now.getMinutes();
this.seconds = this.now.getSeconds();

Also note that clearInterval requires an interval ID to be passed in, which will be returned when you run setInterval

https://developer.mozilla.org/en-US/docs/Web/API/clearInterval

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading