showing something for a certain duration

Viewed 66

I'm making a chat application and for the timestamps in the messages. I want to show 'just now' for like 10 seconds and then 'a few seconds ago' after that 10 seconds. How do I achieve this in the app?

<template>
    <span>{{justNow}}</span>
</template>

<script>
export default{
  data(){
   return{
    time: 'Just Now'  
    }
   },
  computed:{
    justNow(){
       return time; //not sure how do I use setTimeout here
     }
   }
}
</script>
2 Answers

For this, you would want to use a method rather than a computed property, but with a method, you will need to call it, So I have just implemented it into the mounted event. This is because computed properties are designed to return text when a value from the data object has changed, so Timeouts wouldn't make sense.

<template>
    <span>{{time}}</span>
</template>

<script>
export default{
  data(){
   return{
    time: 'Just Now'  
    }
   },
  mounted() {
       setTimeout(() => {
         this.time = "a few seconds ago";
       }, 10000);
     }
   
}
</script>

Although I would recommend using a date library for this like moment.js to do these formats. You can do cool stuff like moment(this.time).fromNow(); and then instead of this.time being "Just Now", you can use the time it was set, and then calculate the time that has passed.

You will also want a way to update this on a timer, so maybe using a setInterval instead of setTimeout might solve this as well.

This is how I would redo it

<template>
    <span>{{displayText}}</span>
</template>

<script>
export default{
  data() {
    return {
      time: timestamp,
      displayText: "Just Now",
    };
  },
  mounted() {
    setInterval(() => {
      this.displayText = this.moment(this.time).fromNow();
    }, 10000);
  },
   
}
</script>

You need to check the duration from timestamp to now. If it less than 10s, use

setTimeout( change the text here, (10 - (currentTime - timestamp)) * 1000)
Related