-1

I have an array of objects that has a property called startedTimestamp. I need to show on the front-end how long ago that has been running, on this case I'm using MomentJS with the fromNow() method. However, that will not updating as the time goes by... to something like 1 minutes ago... and then 2 minutes ago... and so on. Is there a way around that?

I'm using Angular.

Thanks

MrRobot
  • 1,001
  • 1
  • 14
  • 34

1 Answers1

0

I cannot recreate an angular scenario here but it seems setInterval will do the trick. It's important to create the moment object just once (outside setInterval) then the label's text will be updated every second.

Run the code and wait at least a minute and you'll see how it changes from 'a few seconds ago' to 'a minute ago'

const label = document.querySelector('label'),
span = document.querySelector('span');

const m = moment();
let secondsPast = 0;
setInterval(()=>{
  span.textContent = `${++secondsPast} seconds past`
  label.textContent = `${m.fromNow()} from ${m.format()}`
},1000)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>

<span></span><br><br>
<label></label>
Scaramouche
  • 3,188
  • 2
  • 20
  • 46