0

My client wants a debt counter that shows the amount of debt accumulated from Jan. 1, 2016, going up at .80 cents per second. Obviously, I can't have the thing refresh on page load and I looked everywhere for something that would do this. Long story short, I couldn't find what I was looking for, so I thought I could get creative with the code below, using a countdown counter in reverse and may be setting the numbers to equal the correct amount of debt.

Also, I'm not a math guy, so the answer might be looking me in the face.

Here's the code I'm using right now (from Robert Hashemian - hashemian.com):

In my index.html to display counter:

<script language="JavaScript">
TargetDate = "01/01/2016 12:00 AM";
BackColor = "";
ForeColor = "white";
CountActive = true;
CountStepper = 1;
LeadingZero = true;
DisplayFormat = "$%%D%%,%%H%%,%%M%%,%%S%%";
FinishMessage = "It is finally here!";
</script>

Javascript file:

function calcage(secs, num1, num2) {
  s = ((Math.floor(secs/num1))%num2).toString();
  if (LeadingZero && s.length < 2)
    s = "0" + s;
  return "<b>" + s + "</b>";
}

function CountBack(secs) {
  if (secs < 0) {
    document.getElementById("cntdwn").innerHTML = FinishMessage;
    return;
  }
  DisplayStr = DisplayFormat.replace(/%%D%%/g, calcage(secs,86400,100000));
  DisplayStr = DisplayStr.replace(/%%H%%/g, calcage(secs,3600,24));
  DisplayStr = DisplayStr.replace(/%%M%%/g, calcage(secs,60,60));
  DisplayStr = DisplayStr.replace(/%%S%%/g, calcage(secs,1,60));

  document.getElementById("cntdwn").innerHTML = DisplayStr;
  if (CountActive)
    setTimeout("CountBack(" + (secs+CountStepper) + ")", SetTimeOutPeriod);
}

function putspan(backcolor, forecolor) {
 document.write("<span id='cntdwn' style='background-color:" + backcolor + 
                "; color:" + forecolor + "'></span>");
}

if (typeof(BackColor)=="undefined")
  BackColor = "white";
if (typeof(ForeColor)=="undefined")
  ForeColor= "black";
if (typeof(TargetDate)=="undefined")
  TargetDate = "12/31/2020 5:00 AM";
if (typeof(DisplayFormat)=="undefined")
  DisplayFormat = "%%D%% Days, %%H%% Hours, %%M%% Minutes, %%S%% Seconds.";
if (typeof(CountActive)=="undefined")
  CountActive = true;
if (typeof(FinishMessage)=="undefined")
  FinishMessage = "";
if (typeof(CountStepper)!="number")
  CountStepper = -1;
if (typeof(LeadingZero)=="undefined")
  LeadingZero = true;


CountStepper = Math.ceil(CountStepper);
if (CountStepper == 0)
  CountActive = false;
var SetTimeOutPeriod = (Math.abs(CountStepper)-1)*1000 + 990;
putspan(BackColor, ForeColor);
var dthen = new Date(TargetDate);
var dnow = new Date();
if(CountStepper>0)
  ddiff = new Date(dnow-dthen);
else
  ddiff = new Date(dthen-dnow);
gsecs = Math.floor(ddiff.valueOf()/1000);
CountBack(gsecs);

I'm not married to any of the code or ideas above if someone has a better one. Thanks to anyone willing to help!

1 Answers1

2

This should get you started. First get the current balance then update it every second using setInterval. You can do all your rendering from within the setInterval function.

var date1 = new Date("01/01/2016 00:00:00");
var date2 = new Date();

var diff = (date2.getTime() - date1.getTime())/1000;
var debt = diff*.80

setInterval ( function() {
  
   debt += .80;
   console.log(debt.toFixed(2));
   
  
  }, 1000);

or something like this

const date1 = new Date("01/01/2016 00:00:00");
setInterval ( function() {
   var date2 = new Date();
   var diff = (date2.getTime() - date1.getTime())/1000;
   var debt = diff*.80
   console.log(debt.toFixed(2));

  }, 1000);
Luke Kot-Zaniewski
  • 1,161
  • 11
  • 12
  • 1
    This is one possible solution, however, it will not be accurate as the setInterval() runs aprox ever 1000 ms not exactly. A more accurate way to do this would be to recalculate lines 2-5 every time. The calculation is not that computationally heavy and it will eliminate drift. ... its basically a trade off of extra compute time for extra accuracy. – CaffeineAddiction Oct 13 '16 at 20:47
  • agreed but I don't think OP needs pinpoint accuracy here, it's why I also completely ignored the effects of time dilation, you know in case this clock runs on some spaceship accelerating away from the earth ;-) – Luke Kot-Zaniewski Oct 13 '16 at 20:53
  • 1
    @LucasKot-Zaniewski lol @ your remark – but the variance in `setTimeout` and `setInterval` is actually pretty severe, especially if other computations are happening. It wouldn't be uncommon to see intervals of 990 ms or 1010 ms. That's a 2% margin of error *every* interval; which is pretty significant. – Mulan Oct 13 '16 at 20:57
  • For those interested: I did a little write-up on using deltas with `setTimeout` here: http://stackoverflow.com/a/31499056/633183 – `setTimeout`/`setInterval` variance is quite surprising, imo. – Mulan Oct 13 '16 at 20:59
  • You guys are amazing! Thanks so much! I'll try this stuff out and report back. – Chiko032 Oct 13 '16 at 21:02
  • @LucasKot-Zaniewski I agree OP doesn't need pin point accuracy but its possible that someone might want it to have a correct value after switching to a new tab and then going back to it an hour later. In some cases setInterval will not fire if the page does not have focus. – CaffeineAddiction Oct 13 '16 at 21:13
  • wow I didn't realize that switching between tabs could create such differences... – Luke Kot-Zaniewski Oct 13 '16 at 21:15
  • although its pretty onpoint with the tab in focus, I was actually expecting a worse result. I guess the browser has to really allocate its resources on a need basis – Luke Kot-Zaniewski Oct 13 '16 at 21:16
  • @LucasKot-Zaniewski for your example its not that big of a deal, but if you are messing with canvas rendering in a 21fps animation loop the drift can cause nasty consequences. – CaffeineAddiction Oct 13 '16 at 21:20
  • Is RAF any better? – Luke Kot-Zaniewski Oct 13 '16 at 21:24