用 JavaScript 制作实时时钟
Posted
技术标签:
【中文标题】用 JavaScript 制作实时时钟【英文标题】:Making a live clock in javascript 【发布时间】:2022-01-04 05:29:24 【问题描述】:时钟有点用。但它不是替换当前时间,而是每秒打印一个新时间。我明白为什么会这样,但我不知道如何解决它。如果您能在不直接说出答案的情况下给我一些提示,我将不胜感激。谢谢你。这是我的代码:
function time()
var d = new Date();
var s = d.getSeconds();
var m = d.getMinutes();
var h = d.getHours();
document.write(h + ":" + m + ":" + s);
setInterval(time,1000);
【问题讨论】:
好吧,document.write
只是在文档中添加内容,因此您将获得多行输出。您想替换输出而不是继续添加。
【参考方案1】:
添加一个 span 元素并更新其文本内容。
var span = document.getElementById('span');
function time()
var d = new Date();
var s = d.getSeconds();
var m = d.getMinutes();
var h = d.getHours();
span.textContent =
("0" + h).substr(-2) + ":" + ("0" + m).substr(-2) + ":" + ("0" + s).substr(-2);
setInterval(time, 1000);
<span id="span"></span>
答案已更新 [2021] https://***.com/a/67149791/7942242
【讨论】:
谢谢!甚至没有考虑到这一点。应该明白的。不管怎样,谢谢! @williamganrot : 很高兴为您提供帮助【参考方案2】:您还可以在 Date() 上使用 toLocaleTimeString() 来获取显示日期,而不是通过这么多变量来创建。
window.onload = displayClock();
function displayClock()
var display = new Date().toLocaleTimeString();
document.body.innerhtml = display;
setTimeout(displayClock, 1000);
【讨论】:
【参考方案3】:这是我的回答,希望对你有帮助。
<html>
<body>
<script type="text/javascript" charset="utf-8">
let a;
let time;
setInterval(() =>
a = new Date();
time = a.getHours() + ':' + a.getMinutes() + ':' + a.getSeconds();
document.getElementById('time').innerHTML = time;
, 1000);
</script>
<span id="time"></span>
</body>
</html>
我使用了setInterval
箭头函数并在外部声明了变量a
、time
以避免重复分配,其中span id(时间)运行指定的时间间隔(这里是1000)和document.getElementById("time")
调用通过指定 ID 为您获取元素,并将该元素的 innerHTML
设置为 time
的值。
【讨论】:
如果您能在答案中解释您的代码解决了什么问题,而不是仅仅发布一些代码,那就太好了... 我已经用解释更新了我的答案,@Klaassiek,谢谢,这是我第一次回答,不会再重复了。【参考方案4】:请点击这个链接https://codepen.io/uniqname/pen/eIApt你会得到你想要的时钟或试试这个代码
<!DOCTYPE html>
<html>
<head>
<script>
function startTime()
var today = new Date();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML =
h + ":" + m + ":" + s;
var t = setTimeout(startTime, 500);
function checkTime(i)
if (i < 10) i = "0" + i; // add zero in front of numbers < 10
return i;
</script>
</head>
<body onload="startTime()">
<div id="txt"></div>
</body>
</html>
【讨论】:
问题说明如果你能在不直接说出答案的情况下给我一些提示【参考方案5】:只需使用new Date().toLocaleTimeString()
,它就会给你想要的。
setInterval(
() => console.log(new Date().toLocaleTimeString()),
1000
);
【讨论】:
【参考方案6】:代码将以数字格式显示时钟
function myClock()
setTimeout(function()
const d = new Date();
const n = d.toLocaleTimeString();
document.getElementById("demo").innerHTML = n;
myClock();
, 1000)
myClock();
<html>
<body>
<div id="demo"></div>
</body>
</html>
【讨论】:
以上代码将以数字格式显示时钟 请尽量给出正确的答案解释。【参考方案7】:这可以使用 ES6 很好地完成。
const clock12 = document.getElementById('clock12')
const clock24 = document.getElementById('clock24')
// Concatenate a zero to the left of every single digit time frame
function concatZero(timeFrame)
return timeFrame < 10 ? '0'.concat(timeFrame) : timeFrame
function realTime()
let date = new Date()
let sec = date.getSeconds()
let mon = date.getMinutes()
let hr = date.getHours()
// 12 hour time
// If the hour equals 0 or 12, the remainder equals 0, so output 12 instead. (0 || 12 = 12)
clock12.textContent = `$concatZero((hr % 12) || 12) : $concatZero(mon) : $concatZero(sec) $hr >= 12 ? 'PM' : 'AM'`
// 24 hour time
clock24.textContent = `$concatZero(hr) : $concatZero(mon) : $concatZero(sec)`
setInterval(realTime, 1000)
body,
html
height: 100%;
display: grid;
div
margin: auto;
font-size: 2rem;
font-family: consolas;
<div>
<p id="clock12"></p>
<p id="clock24"></p>
</div>
【讨论】:
【参考方案8】:如果这是你问题的根源
但不是替换当前时间,而是每秒打印一个新的时间。
那么你不能让Date object 响应,因为
JavaScript Date 对象以独立于平台的格式表示单个时刻。
如果你不希望每秒创建一个新对象,你可以注册一个专用的Web worker,它每秒调用performance.now(),但这比简单地创建Date对象对系统资源的要求更高,这只是复制实际的 system 时钟(因此不会创建单独的过程来测量时间)。 tl;dr: 只需像你一样每秒创建一个新的 Date 对象。
您的document.write()
问题的根源源于this:
因为 document.write() 写入文档流,所以在已关闭(已加载)的文档 [在您的情况下为 setInterval] 上调用 document.write() 会自动调用 document.open(),这将清除文档。
要更新部分页面,您通常按照@Pranav 的建议设置某个元素的innerHTML。
【讨论】:
【参考方案9】:<html>
<head>
<script>
function clock()
var clockDiv = document.querySelector("#clock");
return setInterval(() =>
let date = new Date();
let tick = date.toLocaleTimeString();
clockDiv.textContent = tick;
, 1000);
</script>
</head>
<body onload="clock()">
<div id="clock"></div>
</body>
</html>
【讨论】:
【参考方案10】:一个工作演示,点击链接
http://www.w3schools.com/js/tryit.asp?filename=tryjs_timing_clock
更新 您正在使用 document.write ,它每次都会附加当前时间(如果我没有错的话,这就是您的问题)。 因此,用新时间替换以前的时间 - 1.你必须用替换模式打开文档(如下代码所示) 2.你写当前时间 3. 然后关闭文档。
function time()
var d = new Date();
var s = d.getSeconds();
var m = d.getMinutes();
var h = d.getHours();
document.open("text/html", "replace");
document.write(h + ":" + m + ":" + s);
document.close();
setInterval(time,1000);
【讨论】:
虽然这在理论上可以回答这个问题,it would be preferable 在此处包含答案的基本部分,并提供链接以供参考。 @MikeMcCaughan,我已经更新了我的答案,希望这会有所帮助。【参考方案11】:有人想知道如何编写带闹钟的数字时钟吗?这是我的代码笔http://codepen.io/abhilashn/pen/ZLgXbW
function AmazeTime(almbtnobj)
this.date,this.day,this.dt,this.month, this.year,this.hour,this.minute,this.second = null;
this.almHour, this.almMinute, almMeridiem = null;
this.meridiem = "AM";
this.almBtn = almbtnobj;
this.almBtn = this.setAlarm;
AmazeTime.prototype.initializeTime = function()
this.dt = new Date();
this.day = this.getDayInWords(this.dt.getDay());
this.date = this.dt.getDate();
this.month = this.getMonthInShort(this.dt.getMonth());
this.year = this.dt.getFullYear();
this.hour = this.setHour(this.dt.getHours());
this.minute = this.doubleDigit(this.dt.getMinutes());
this.second = this.doubleDigit(this.dt.getSeconds());
this.meridiem = this.setMeridiem(this.dt.getHours());
AmazeTime.prototype.setHour = function(hr)
if(hr > 12)
hr = hr - 12;
if(hr === 0)
hr = 12;
return this.doubleDigit(hr);
AmazeTime.prototype.doubleDigit = function(val)
if(val < 10)
val = "0" + val;
return val;
AmazeTime.prototype.setMeridiem = function(hr)
if(hr > 12)
hr = hr - 12;
return "PM";
else
return "AM";
AmazeTime.prototype.getMonthInShort = function(value)
switch(value)
case 0:
return "Jan";
break;
case 1:
return "Feb";
break;
case 2:
return "Mar";
break;
case 3:
return "Apr";
break;
case 4:
return "May";
break;
case 5:
return "Jun";
break;
case 6:
return "Jul";
break;
case 7:
return "Aug";
break;
case 8:
return "Sep";
break;
case 9:
return "Oct";
break;
case 10:
return "Nov";
break;
case 11:
return "Dec";
break;
AmazeTime.prototype.getDayInWords = function(value)
switch(value)
case 0:
return "Sunday";
break;
case 1:
return "Monday";
break;
case 2:
return "Tuesday";
break;
case 3:
return "Wednesday";
break;
case 4:
return "Thursday";
break;
case 5:
return "Friday";
break;
case 6:
return "Saturday";
break;
AmazeTime.prototype.setClock = function()
var clockDiv = document.getElementById("clock");
var dayDiv = document.getElementById("day");
var dateDiv = document.getElementById("date");
var self = this;
dayDiv.innerText = this.day;
dateDiv.innerText = this.date + " " + this.month + " " + this.year;
clockDiv.innerHTML = "<span id='currentHr'>" + this.hour + "</span>:<span id='currentMin'>" + this.minute + "</span>:" + this.second + " <span id='meridiem'>" + this.meridiem + "</span>";
AmazeTime.prototype.setAlarm = function()
this.almHour = this.doubleDigit(document.getElementById('almHour').value);
this.almMinute = this.doubleDigit(document.getElementById('almMin').value);
if(document.getElementById("am").checked == true)
this.almMeridiem = "AM";
else
this.almMeridiem = "PM";
AmazeTime.prototype.checkAlarm = function()
var audio = new Audio('http://abhilash.site44.com/images/codepen/audio/audio.mp3');
if(this.hour == this.almHour && this.minute == this.almMinute && this.almMeridiem == this.meridiem)
audio.play();
if(this.minute > this.almMinute)
audio.pause();
var mytime = null;
mytime = new AmazeTime(document.getElementById("savebtn"));
window.addEventListener('load', function()
function runTime()
mytime.initializeTime();
mytime.setClock();
mytime.checkAlarm();
setInterval(runTime, 1000);
, false);
function saveAlarm()
mytime.setAlarm();
$('#myModal').modal('hide');
document.getElementById("savebtn").addEventListener("click", saveAlarm , false);
body background:#A3ABF2; font-family:Arial; text-align:center;
.day font-size:64px;
.date font-size:33px;
.clock font-size:44px;
.clock-content margin-top:35vh; color:#FFF;
.alarm-icon font-size:34px; cursor:pointer; position:absolute; top:15px; right:15px; color:#FFF;
.setalmlbl padding-right:20px;
.setalmtxtbox margin-right:10px; width:60px;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<i id="alarmbtn" data-toggle="modal" data-target="#myModal" class="fa fa-bell alarm-icon"></i>
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel"> Set Alarm</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<form>
<div class="modal-body">
<div class="form-inline">
<label for="hours" class="setalmlbl" >Hours </label>
<select class="form-control setalmtxtbox" name="almHour" id="almHour">
<script>
for(var h = 1; h <= 12; h ++)
document.write("<option value="+ h +">" + h + "</option>");
</script>
</select>
<label for="minutes" class="setalmlbl"> Minutes </label>
<select class="form-control setalmtxtbox" name="almMin" id="almMin">
<script>
for(var m = 1; m <= 60; m++)
document.write("<option value="+ m +">" + m + "</option>");
</script>
</select>
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input" type="radio" name="meridiem" id="am" value="am" checked>
A.M.
</label>
</div>
<div class="form-check">
<label class="form-check-label">
<input class="form-check-input" type="radio" name="meridiem" id="pm" value="pm">
P.M.
</label>
</div>
</form>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="submit" id="savebtn" class="btn btn-primary">Save</button>
</div>
</div>
</div>
</div>
<div class="container-fluid">
<div class="clock-content">
<div class="day" id="day"></div>
<div class="date" id="date"></div>
<div class="clock" id="clock"></div>
</div>
</div>
【讨论】:
【参考方案12】:您可以在 app.js 中查看这个简单的 javascript 时钟,以在浏览器中查看实时时钟https://github.com/danielrussellLA/simpleClock
var clock = document.getElementById('clock');
setInterval(function()
clock.innerHTML = getCurrentTime();
, 1);
function getCurrentTime()
var currentDate = new Date();
var hours = currentDate.getHours() > 12 ? currentDate.getHours() - 12 : currentDate.getHours();
hours === 0 ? hours = 12 : hours = hours;
var minutes = currentDate.getMinutes();
var seconds = currentDate.getSeconds() < 10 ? '0' + currentDate.getSeconds() : currentDate.getSeconds();
var currentTime = hours + ':' + minutes + ':' + seconds;
return currentTime;
【讨论】:
【参考方案13】:试试这样的。
new Date()
会给你今天的日期。获取日期后,获取距今天日期的小时、分钟、秒。
setTimeout(startTime, 1000)
将帮助您连续运行计时器。
<!DOCTYPE html>
<html>
<body onload="startTime()">
<h2>JavaScript Clock</h2>
<div id="txt"></div>
<script>
function startTime()
const today = new Date();
let h = today.getHours();
let m = today.getMinutes();
let s = today.getSeconds();
m = checkTime(m);
s = checkTime(s);
document.getElementById('txt').innerHTML = h + ":" + m + ":" + s;
setTimeout(startTime, 1000);
function checkTime(i)
if (i < 10) i = "0" + i; // add zero in front of numbers < 10
return i;
</script>
</body>
</html>
【讨论】:
【参考方案14】:“一天中的新时间”是什么意思?但是为了替换新的时间,你可以创建一个包含时间的 div,并且每次调用 time() 时,设置 div.innerHTML = "",如下所示
HTML:
<div id="curr_time"></div>
JS:
var div = document.getElementById('curr_time');
function time()
div.innerHTML = "";
var d = new Date();
var s = d.getSeconds();
var m = d.getMinutes();
var h = d.getHours();
div.innerHTML = h + ":" + m + ":" + s;
setInterval(time, 1000);
【讨论】:
以上是关于用 JavaScript 制作实时时钟的主要内容,如果未能解决你的问题,请参考以下文章