Reputation: 1145
I am creating certain table rows dynamically using jquery , I want to display created ago in seconds in that row, I tried below code
var currenttime = moment();
$(".tbody").append("<tr><td class='tdata' data-id='"+currenttime+"'>0 seconds</td></tr>");
setInterval(function(){
var latest = moment();
var oldtime = $(".tdata").data("id");
var newtime = oldtime-latest;
$(".tdata").html(newtime+ "secs");
}, 3000);
So basically i am storing current time while row creation and then checking randomly and displaying the total seconds (not minutes or hours) , if 5 mins it should display 300.
I tried var later = moment(); , but it creates object i cannot store it in data-attribute , it will be great even if it can be done without momentjs , any ideas please , thnank you.
Upvotes: 0
Views: 194
Reputation: 2562
Little change
var starts = Date.now();
//...
var diff = (Date.now() - starts) / 10000;
You can also check moment.duration since your already using momentJS.
Upvotes: 1
Reputation: 5148
You don't need moment here but just Date (getTime() method)
var currenttime = new Date().getTime(); // Count milliseconds since 1970
$(".tbody").append("<tr><td class='tdata' data-id='"+currenttime+"'>0 seconds</td></tr>");
setInterval(function(){
var oldtime = parseInt($(".tdata").data("id")); // HTML store it as String, don't forget to transform it to int "14254782000" > 14254782000
var seconds = parseInt((new Date().getTime() - oldtime) / 1000);
$(".tdata").html(seconds+ " secs");
}, 1000);
This way you're not storing a moment object but a number of seconds (int), also it's always Now - Past (and not Past - Now) because Now is higher than Past (and we want a positive value).
Upvotes: 1
Reputation: 12637
Don't know what to explain about this example:
$("button").on("click", function(){
$("tbody").append("<tr><td class='tdata'><span data-seconds-since=" + Date.now() + ">0</span> seconds</td></tr>");
});
// updates all places at once
setInterval(function(){
var now = Date.now();
$("[data-seconds-since]").text(function(){
return ((now - this.dataset.secondsSince) / 1000).toFixed(1)
});
}, 40);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table><tbody></tbody></table>
<button type="button">Add Row</button>
Upvotes: 1