好的,让我们说,我们有一个网站,需要一个实时;
例子:
<div id="updatetime">21:12:52</div>
每秒钟更新时间:m:秒。
我脑子里想的是用interval function做长池,然后把sec +1加到60,然后把+1加到m上,和小时一样。但是,是否有一个函数已经解决了这个问题呢?
如何使这个21:12:52 成为一个移动的真正时钟,并使用javascript每秒钟更新一次?
我有搜索谷歌,堆栈溢出,其中许多告诉我们如何使当前的实时日期从javascript。但从现存的时间来看都没有。如果有,请插入链接。
发布于 2012-06-07 12:03:43
它可以这么简单:
setInterval(function(){
document.getElementById("updatetime").innerHTML = (new Date()).toLocaleTimeString();
}, 1000);或者使用其他日期方法对输出进行微调。
更新
我现在才意识到OP不是在用当前时间递增一个元素,而是要求一个预先确定的时间。
这不是那么简单,但这里有一个解决方案,应该符合最初的问题:
function increment_time_element(element, delay) {
var interval, last,
time_pattern = /(\d+):(\d+):(\d+)/,
start = element.innerHTML.match(time_pattern),
then = new Date;
then.setHours (parseInt(start[1], 10) || 0);
then.setMinutes(parseInt(start[2], 10) || 0);
then.setSeconds(parseInt(start[3], 10) || 0);
function now() {
return Date.now ? Date.now() : (new Date).getTime();
}
last = now();
interval = setInterval(function () {
var current = now();
// correct for any interval drift by using actual difference
then.setTime(then.getTime() + current - last)
last = current;
element.innerHTML = then.toString().match(time_pattern)[0];
}, delay || 1000);
return {cancel: function() { clearInterval(interval) }};
}
// Usage:
var incrementing_time =
increment_time_element(document.getElementById("updatetime"));
// Then, if you want to cancel:
incrementing_time.cancel();发布于 2012-06-07 12:19:58
如果你不需要非常高的保真度,你可以这样做:
var container = document.getElementById("updatetime").firstChild;
var values = container.nodeValue.split(":");
// Because there is only a datetime specified, I assume is the current date
var now = new Date();
var time = new Date(now.getFullYear(), now.getMonth(), now.getDate(),
values[0], values[1], values[2]).getTime();
setInterval(function() {
time += 1000;
var date = new Date(time);
var values = [date.getHours(), date.getMinutes(), date.getSeconds()];
for (var i = 0; i < 3; i++)
if (values[i] < 10)
values[i] = "0" + values[i];
container.nodeValue = values.join(":");
}, 1000);如果您希望更多地与当前计算机时钟同步,那么我建议您使用setTimeout并根据适当的运行时间调整delay参数。
update :由于注释,似乎要更新的元素不仅是一个和多个,而且代码使用的是jQuery。在这里,一种使用class识别多个元素的方法:
var containers = $(".updatetime");
var times = [];
var now = new Date();
containers.each(function(index, node) {
var values = $(node).text().split(":");
times[index] = new Date(
now.getFullYear(), now.getMonth(), now.getDate(),
values[0], values[1], values[2]).getTime();
});
setInterval(function() {
containers.each(function(index, node) {
times[index] += 1000;
var date = new Date(times[index]);
var values = [date.getHours(), date.getMinutes(), date.getSeconds()];
for (var i = 0; i < 3; i++)
if (values[i] < 10)
values[i] = "0" + values[i];
$(node).text(values.join(":"));
});
}, 1000);发布于 2012-11-08 13:58:24
如果你的实时时钟在滴答作响,看看我在创建“翻转时钟”时使用的代码。我把每个数字分割成一个单独的数字,用于时钟内的图形放置,但是如果你把它去掉,你就只有更新的文本了。
https://stackoverflow.com/questions/10931197
复制相似问题