Home > Software engineering >  Check if an element was created less than x seconds ago
Check if an element was created less than x seconds ago

Time:11-05

Problem

I want to check if an element was created less than 60 seconds ago. Hence, using vue, the text should automatically turn from

Is this text younger than 60 seconds? true

to

Is this text younger than 60 seconds? false

after 60 seconds.

However, it seems that either the setTimeout does not run at all or that Date.now() within the setTimout does not update. How can I solve this?

html

<div id="app">
  Is this text younger than 60 seconds?
  <br>
  {{ isNew }}
</div>

js

new Vue({
  el: "#app",
  data: {
        isNew: false
  },
  methods: {
    checkIfIsNew() {
      let dateTimeToCheck = Date.parse("2021-11-03 18:16:00") // replace this hardcodeed datetime
      let seconds = (Date.now() - dateTimeToCheck) / 1000;
      console.log(seconds);
      if (seconds < 60) {
        this.isNew = true;
      } else {
        this.isNew = false;
      }
      if (this.isNew) {
        setTimeout(this.checkIfIsNew, 10*1000);
      }
    },
  },
  created() {
    this.checkIfIsNew();
  },
})

https://jsfiddle.net/mhr5y1dp/

CodePudding user response:

The problem is in the code that you didn't post in your question, namely how do you set the dateTimeToCheck. I think you are setting this value less than a minute older than Date.now() on every invocation of checkIfIsNew. Instead you should set this value outside this function or to a constant value.

For example in this fiddle the dateTimeToCheck is set to creation time of the component in data and the code runs just fine.

new Vue({
  el: "#app",
  data: {
        isNew: false,
        dateTimeToCheck: Date.now()
  },
  methods: {
    checkIfIsNew() {
        // let dateTimeToCheck = Date.parse("2021-11-03 18:16:00") // replace this hardcoded datetime
      let seconds = (Date.now() - this.dateTimeToCheck) / 1000;
      console.log(seconds);
      if (seconds < 60) {
        this.isNew = true;
      } else {
        this.isNew = false;
      }
      if (this.isNew) {
        setTimeout(this.checkIfIsNew, 10*1000);
      }
    },
  },
  created() {
    this.checkIfIsNew();
  },
})
  • Related