Advertisement
rAthus

JavaScript timer live elapsed time from timestamp

May 17th, 2023 (edited)
707
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // example : <span since="578556600"></span>
  2.  
  3. function updateSince($this) {
  4.     var ts_since = $this.attr('since')*1;
  5.     var ts_now = Math.round(Date.now()/1000);
  6.     var s_total = Math.max(ts_now-ts_since,0);
  7.     var y = Math.floor(s_total/31536000);
  8.     var m = Math.floor(s_total/2592000);
  9.     var d = Math.floor(s_total/86400);
  10.     var h = Math.floor(s_total/3600);
  11.     var i = Math.floor((s_total-h*3600)/60);
  12.     var s = s_total-h*3600-i*60;
  13.     if (y)
  14.         $this.html(y+' year'+((y>1)?'s':''));
  15.     else if (m)
  16.         $this.html(m+' month'+((m>1)?'s':''));
  17.     else if (d)
  18.         $this.html(d+' day'+((d>1)?'s':''));
  19.     else if (h)
  20.         $this.html(h+' hour'+((h>1)?'s':''));
  21.     else if (i)
  22.         $this.html(i+' minute'+((i>1)?'s':''));
  23.     else if (s>20)
  24.         $this.html('a few moments');
  25.     else
  26.         $this.html('a few seconds');
  27. }
  28. jQuery('[since]').each(function() {
  29.     var $this = jQuery(this);
  30.     updateSince($this);
  31.     var interval = setInterval(function() {
  32.         updateSince($this);
  33.     },1000);
  34. });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement