gpt4 book ai didi

javascript - 如何用 JavaScript 制作毫秒计时器?

转载 作者:行者123 更新时间:2023-12-01 02:39:00 27 4
gpt4 key购买 nike

我找到了如何在 javascript (Jquery) 中制作一个毫秒时钟(参见代码片段),但我不知道如何仅以毫秒制作一个计时器。我尝试创建一个循环,将 1000 添加到“milli”的值,但我的条件从未完全起作用

// START CLOCK SCRIPT

Number.prototype.pad = function(n) {
for (var r = this.toString(); r.length < n; r = 0 + r);
return r;
};

function updateClock() {
var now = new Date();
var milli = now.getMilliseconds(),
sec = now.getSeconds(),
min = now.getMinutes(),
hou = now.getHours(),
mo = now.getMonth(),
dy = now.getDate(),
yr = now.getFullYear();
var months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
var tags = ["mon", "d", "y", "h", "m", "s", "mi"],
corr = [months[mo], dy, yr, hou.pad(2), min.pad(2), sec.pad(2), milli];
for (var i = 0; i < tags.length; i++)
document.getElementById(tags[i]).firstChild.nodeValue = corr[i];
}

function initClock() {
updateClock();
window.setInterval("updateClock()", 1);
}

// END CLOCK SCRIPT
body {background-color:#666;}

#timedate {
font: small-caps bold 43px/150% Arial, Helvetica, sans-serif;
text-align:left;
width: 50%;
margin: 20px auto;
color:#333;
border-left: 20px solid yellow;
padding: 20px;
}
<body onLoad="initClock()">

<div id="timedate">
<a id="mon">January</a>
<a id="d">1</a>,
<a id="y">0</a><br />
<a id="h">12</a> :
<a id="m">00</a>:
<a id="s">00</a>:
<a id="mi">000</a>
</div>

最佳答案

您可以使用Date API中的getTime函数,它返回1970/01/01之后的毫秒数。

function updateClock(initTime) {
var now = new Date();
var milli = now.getTime() - initTime;
document.getElementById('timedate').innerHTML = milli;
}

function initClock() {
var initTime = new Date().getTime();
updateClock();
window.setInterval(updateClock, 1, initTime);
}

关于javascript - 如何用 JavaScript 制作毫秒计时器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47700976/

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