Any jquery plugin which automatic update time for all the posts of a page

后端 未结 3 798
有刺的猬
有刺的猬 2021-01-28 15:34

I have a page having lots of posts showing time when they were posted. I want to keep on updating that time after every 1 min. One simple way can be give them a same class and g

3条回答
  •  后悔当初
    2021-01-28 16:09

    You can use a simple plugin like this:

    $.fn.UpdateSince = function(interval) {
    
        var times = this.map(function(){ return { e: $(this), t: parseInt($(this).html()) }; });
    
        var format = function(t) {
            if (t > 60) {
                return Math.floor(t / 60) + ' minutes ago'
            } else {
                return t + ' seconds ago';
            }
        }
    
        var update = function(){
            var now = new Date().getTime();
            $.each(times, function(i, o){
                o.e.html(format(Math.round((now - o.t) / 1000)));
            });
        };
    
        window.setInterval(update, interval);
        update();
    
        return this;
    }
    

    It sets up a function that runs at an interval and updates the elements that you specify. The elements originally contain the time in integer format, i.e. milliseconds since 1970-01-01:

    1314952218779

    Usage:

    $('.TimeSince').UpdateSince(1000);
    

    The parameter is the update interval in milliseconds. 1000 is once a second, so if you display the time in minutes you would use a larger value, for example every 20 seconds, or 20 * 1000.

    The part you would want to improve is the function format, which turns seconds into a human readable format. It now has minutes and seconds ago, but you probably want something like, days, hours or minutes ago.

    Demo: http://jsfiddle.net/Guffa/7EsAX/

提交回复
热议问题