Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

112
Vistas
Check if an element was created less than x seconds ago

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/

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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();
  },
})
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda