How to implement a live and persistent number counter on a site
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 concep开发者_开发技巧ts and fundamentals, and I can read a script and figure out what's going on. Any ideas or suggestions would be very appreciated.
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.
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;
精彩评论