如何在站点上实现实时和持久数字计数器 [英] How to implement a live and persistent number counter on a site
问题描述
我有一个回收罐头的客户。我们正在为他们开发一个新的网站,他们希望在他们的网站上有一个现场罐头处理柜台。起始编号(因为它们已运行一段时间)将大约为50,000,000,并且没有结束编号。
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.
要获得处理速率,我们可以平均每年处理的罐数并获得时间估计,例如每10秒1罐。但是我如何实现一个持久计数器,以便计数器不会在页面加载/刷新时从设定值开始滴答?
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?
我是一个初学者使用javascript和jQuery,但我确实理解编程概念和基础知识,我可以阅读脚本并弄清楚发生了什么。任何想法或建议都将非常感激。
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.
推荐答案
今年年初:
var start = new Date(2011, 0, 1); // Note the 0!
计算已经过了多长时间:
Calculate how much time has elapsed:
var elapsed = new Date() - start; // In milliseconds
假设您的费率为每10秒1罐:
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
优化可能是让您的更新间隔与已知费率保持一致,但最好是将您的演示文稿更新与费率信息分开。
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.
这篇关于如何在站点上实现实时和持久数字计数器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!