timeAgo Single Element

by Christopher O

HTML

<span title="1512917205" class="timeago">a</span><br>
<span title="1481208848" class="timeago">b</span><br>
<span title="1454587987" class="timeago">c</span><br>
<span title="1454587987" id="blabla">d</span><br>

JavaScript

console.clear();

function getRandomInt(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
}

var TAtemplateProps = {
    prefix: "",
    suffix: "",
    seconds: "0m",
    minute: "1m",
    minutes: "%dm",
    hour: "1h",
    hours: "%dh",
    day: "1d",
    days: "%dd",
    month: "1mo",
    months: "%dmo",
    year: "1y",
    years: "%dy"
};

var TAtemplate = function (t, n) {
    return TAtemplateProps[t] && TAtemplateProps[t].replace(/%d/i, Math.abs(Math.round(n)));
};

var TAsingle = function (pastTime,now) {
    if (!pastTime) return;
    if(!Number.isInteger(pastTime)){
      pastTime = pastTime.replace(/\.\d+/, ""); // remove milliseconds
      pastTime = pastTime.replace(/-/, "/").replace(/-/, "/");
      pastTime = pastTime.replace(/T/, " ").replace(/Z/, " UTC");
      pastTime = pastTime.replace(/([\+\-]\d\d)\:?(\d\d)/, " $1$2"); // -04:00 -> -0400
  	}
  	pastTime = new Date(pastTime * 1000 || pastTime);
  
    //var now = new Date();
    var seconds = ((now.getTime() - pastTime) * 0.001) >> 0;
    var minutes = seconds / 60;
    var hours = minutes / 60;
    var days = hours / 24;
    var years = days / 365;

    return TAtemplateProps.prefix + (seconds < 45 && TAtemplate('seconds', seconds) || seconds < 90 && TAtemplate('minute', 1) || minutes < 45 && TAtemplate('minutes', minutes) || minutes < 90 && TAtemplate('hour', 1) || hours < 24 && TAtemplate('hours', hours) || hours < 42 && TAtemplate('day', 1) || days < 30 && TAtemplate('days', days) || days < 45 && TAtemplate('month', 1) || days < 365 && TAtemplate('months', days / 30) || years < 1.5 && TAtemplate('year', 1) || TAtemplate('years', years)) + TAtemplateProps.suffix;
};


var cacheTimeTA = 0;
function timeAgo() {
    // console.log('timeAgo');
    var now = new Date();
    ts = Math.round(now.getTime() / 1000);

		// Ignore if already run in last min
    if(cacheTimeTA > ts) return;
    cacheTimeTA = ts + 60;

    var elements =...