我想帮助制作我在Javascript / HTML实时创建的时钟。
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="style.css">
<script>
function timer() {
var today = new Date();
var hrs = today.getHours();
var mins = today.getMinutes();
var secs = today.getSeconds();
var mili = today.getMilliseconds();
document.getElementById('txt').innerHTML = "Since midnight, " + hrs + " hours, " + mins + " minutes, " + secs + " seconds, and " + mili + " milliseconds have passed.";
}
</script>
</head>
<body onload="timer()">
<div id="txt"></div>
<body>
<h1>Clock</h1>
</body>
</html>
任何帮助都将不胜感激。
答案 0 :(得分:1)
您应该创建一个间隔计时器,并且每隔X毫秒调用一次计时器功能,因为您显示毫秒级的精度,您可能希望将其保持为100毫秒。我建议使用setInterval
。把它放在你的脚本块中:
setInterval(timer, 100);
以下是一个完整的例子:
function timer() {
var today = new Date();
var hrs = today.getHours();
var mins = today.getMinutes();
var secs = today.getSeconds();
var mili = today.getMilliseconds();
document.getElementById('txt').innerHTML = "Since midnight, " + hrs + " hours, " + mins + " minutes, " + secs + " seconds, and " + mili + " milliseconds have passed.";
}
setInterval(timer, 100);
&#13;
<div id="txt"></div>
&#13;
答案 1 :(得分:0)
使用setTimeout函数(参见window.setTimeout)
在你的情况下: 调用定时器功能并添加
window.setTimeout(timer, 50);
在函数的最后。
示例:
function timer() {
var today = new Date();
var hrs = today.getHours();
var mins = today.getMinutes();
var secs = today.getSeconds();
var mili = today.getMilliseconds();
document.getElementById('txt').innerHTML = "Since midnight, " + hrs + " hours, " + mins + " minutes, " + secs + " seconds, and " + mili + " milliseconds have passed.";
window.setTimeout(timer, 50);
}
timer();
<div id="txt"></div>