简体   繁体   中英

How do I update time on multiple rows using javascript

I'm using the fromNow function from moment.js library to display time elapsed from a specific date/time (eg '16 hours ago'). I use this within a table on multiple rows within my web app.

This part works fine, but I need the time to count continuously and for several rows (50 - 60 and growing). How do I get the time to count continuously and efficiently? I say efficiently because, I've read that using interval may be a bad idea so I'm not sure and I need help understanding.

This is how I create a cell which holds the elapsed time:

newCell = row.insertCell(++cellIndex);
  newText = document.createTextNode(moment(data.checkintime).fromNow());
  newCell.appendChild(newText);

Assuming the code you posted is correct, you can save the updated time in a variable and update all the rows. In that way, it's the same time that will display for all the rows and that time would just have to be done in one time:

var updatedTime = moment(data.checkintime).fromNow();
newCell = row.insertCell(++cellIndex);
newText = document.createTextNode(updatedTime);
newCell.appendChild(newText);

If you want the timestamp to continuously update, look into a library such as TimeAgo .

With your current code, simply change the text node to match timaeago's syntax <abbr title='{timestamp}' class='timeago'> and add the following javascript to the bottom of your page

jQuery(document).ready(function() { jQuery("abbr.timeago").timeago(); });

This will continuously update the timestamp ("a moment ago", "2 minutes ago"....) which I believe is what you're looking for

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM