gpt4 book ai didi

javascript - 使用javascript在div中使用现有时间制作一个实时时钟

转载 作者:塔克拉玛干 更新时间:2023-11-02 21:55:23 25 4
gpt4 key购买 nike

好吧,假设我们有一个需要实时时间的网站;

例子:

<div id="updatetime">21:12:52</div>

每秒钟更新 hours:m:second.

我在使用 interval function 时的想法做长池并将 sec +1 if 添加到 60 然后将 + 1 添加到 m 并与小时相同。但是是否有一个函数已经解决了这个问题?

这个怎么做21:12:52每秒更新一次的带有 javascript 的移动真实时钟?

我搜索了 google、stackoverflow,其中很多都告诉我们如何从 javascript 生成当前实时日期时间。但没有一个来自现存的时间。如果有请插入链接。

最佳答案

它可以像这样简单:

setInterval(function(){
document.getElementById("updatetime").innerHTML = (new Date()).toLocaleTimeString();
}, 1000);

或者使用the other Date methods微调您的输出。

更新

我现在才意识到 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();

关于javascript - 使用javascript在div中使用现有时间制作一个实时时钟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10931197/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com