Getting Elapsed Time in JS

有些话、适合烂在心里 提交于 2019-12-13 04:50:30

问题


Fiddle

I am making a social network and when you post something, I want to show the time. I have the current code to display the time (this isn't only the time, it's also validating and posting the text):

$('#b').click(function () {
    var v = $('#type').val();
    var u = $('#input').val();
    if (v !== "" && u !== ""){
        var time = new Date();
        var currentime = Date.now();
        var x = currentime - time;
        $("ul").prepend("<li>" + v + "<br />Posted by " + u + " " + x +" minutes ago  </li>");
        $('#type, #input').css('border','');
    }
    else if (v == "" && u == "") {
        $('#type, #input').css('border','1px solid red');
    }
    else if (v == "") {
        $('#type').css('border','1px solid red');
        $('#input').css('border','');
    }
    else {
        $('#input').css('border','1px solid red');
        $('#type').css('border','');
    }
});

When the time posts, it says 0 minutes ago (like I told it to), but after any amount of time, it still says 0.


回答1:


fiddle

Basically you set up a setInterval which governs ho frequently you update your time attribute. I used a span with a class .time to so you could theoretically update anything with time.

I would go further and hash your posts so you can easily retrieve each posts original time.

EDIT: added a new fiddle.



来源:https://stackoverflow.com/questions/20302008/getting-elapsed-time-in-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!