3

I have a client who recycles cans. We're developing a new web site for them and they want a live "cans processed" counter on their site. The starting number (since they've been in operation for a while) will be around 50,000,000, and there's not an ending number.

To get "process rate" we can average out the number of cans processed per year and get a time estimate such as "1 can per 10 seconds". But how would I implement a "persistent" counter, so that the counter doesn't start ticking off from a set value at page load/refresh?

I'm a beginner with javascript and jQuery, but I do understand programming concepts and fundamentals, and I can read a script and figure out what's going on. Any ideas or suggestions would be very appreciated.

2 Answers2

6

Take the beginning of this year:

var start = new Date(2011, 0, 1); // Note the 0!

Calculate how much time has elapsed:

var elapsed = new Date() - start; // In milliseconds

Let's say your rate is 1 can per 10 seconds:

var rate = 1 / 10 / 1000; // Cans per millisecond

Calculate how many cans have been processed since the beginning of this year:

var cans = Math.floor(elapsed * rate);

So, a simple set up could be:

var start = new Date(2011, 0, 1);
var rate = 1 / 10 / 1000;
var base = 50000000;

setInterval(function () {
    var cans = Math.floor((new Date() - start) * rate) + base;
    $("#cans").text(cans); // I hope you're using jQuery
}, 5000); // update every 5 seconds -- pick anything you like; won't affect result

http://jsfiddle.net/eKDXB/

An optimization could be to keep your update interval aligned with the known rate, but it is probably better to keep your presentation updates decoupled from the rate information.

Ates Goral
  • 137,716
  • 26
  • 137
  • 190
  • Thanks so much for the easily understandable code for us newbies! – David Nov 12 '13 at 22:41
  • @Ates Goral I would like to have 1 can added every 30 seconds, what would I put as the rate? I'm a bit lost at what you're doing with `1 / 10 / 1000`. – Kid Diamond Mar 01 '14 at 17:40
  • 1
    @KidDiamond 1 second is 1000 milliseconds and 10 seconds is 10 * 1000 milliseconds. `1 / 10 / 1000` is a lazy way of saying `1 / (10 * 1000)`. So, if you need a can every 30 seconds, that's `1 / (30 * 1000)` or `(1 / 30 / 1000)`. – Ates Goral Mar 01 '14 at 23:15
  • Aha, that made sense. :) – Kid Diamond Mar 02 '14 at 10:03
1

I think I'd get current epoch with

var msecs = (new Date()).getTime();

and then compute the numbers of cans from that using

var total_number = base_number + (msecs - start_date) / msecs_per_can;
6502
  • 112,025
  • 15
  • 165
  • 265