如何在现有代码中将滴答时钟添加到div中? [英] how can I add the ticking clock to my div in an existing code?
问题描述
实际上是此问题的后续操作 http://jsfiddle.net/nauzilus/rqctam5r/
It's actually a follow up to this question I want to display elements from json based on their time and duration and interval is interupted by settimeout - I accepted the answer there made by @Daniel Flint - his code is quite clear and can be found here http://jsfiddle.net/nauzilus/rqctam5r/
但是,我还想添加一件事-一个简单的div <div id="time"></div>
,它将包含一个新的日期时间对象,该对象在打开页面时进行了初始化,然后每秒增加一次,以不断显示当前时间.我考虑过要在那里写一个javascript:
However, there's one more thing that I wanted to add - a simple div <div id="time"></div>
that would contain a new date time object initialized during opening the page and then it being incremented every second just to show the current time constantly. I thought about writing there a javascript:
var actualTime = new Date(substractedDate); // taken from the server
function updateTimeBasedOnServer(timestamp) {
var calculatedTime = moment(timestamp);
var dateString = calculatedTime.format('h:mm:ss A');
$('#time').html(dateString + ", ");
};
var timestamp = actualTime.getTime();
updateTimeBasedOnServer(timestamp);
setInterval(function () {
timestamp += 1000; // Increment the timestamp at every call.
updateTimeBasedOnServer(timestamp);
}, 1000);
(我在此处提供服务器的时间作为时间戳).
(I provide the time of the server as a timestamp there).
我只是注意到在div中显示时间与屏幕上显示的文本之间存在细微的不匹配,可能是因为我在两个不同的地方都同时增加了两个值.
I just noticed that there is a slight mismatch between displaying the time in my div and between the text appearing on the screen, possibly because I increment both of the values in two different places.
所以我的问题是-我怎样才能将@Daniel Flint的代码与我的代码合并"并且仅将两个值都增加到一个位置?
So my question is - how can I "merge" @Daniel Flint's code with mine and increment both values only in one place?
推荐答案
一件事跳到这里:
timestamp += 1000;
不能保证
setTimeout
/setInterval
严格按照您输入的延迟运行.在浏览器控制台中运行以下命令:
setTimeout
/setInterval
aren't guaranteed to run at precisely the delay you've entered. Run this in your browsers console:
var last = Date.now(),
time = function() {
var now = Date.now();
console.log(now - last);
last = now;
},
id = setInterval(time, 1000);
在我家里的Mac(Chrome/FireFox)上,它的位置介于990到1015之间.Windows机器在工作中性能更好(995-1002),但IE达到了1020.这不是一个很大的区别,但是不是什么.
On my Mac at home (Chrome/FireFox) it was anywhere from 990 to 1015. Windows machine at work is a bit better (995-1002), but IE was getting up to 1020. It's not a huge difference, but it's not nothing.
因此,代码需要能够处理并非每1000毫秒准确运行一次的情况.这就是为什么我以500ms的间隔运行计时器,并检查启动时间是否小于当前时间的原因.
So code needs to be able to handle not running exactly every 1000ms. That's why I was running the timer at 500ms intervals, and checking if the start time was less-than-equal to the current time.
我重新演示了演示,以显示时间和消息同步:
I've rejigged the demo to show the time and message in sync:
(function() {
var messages = [];
var time = document.getElementById("current-time");
var display = document.getElementById("message");
function check() {
showMessage(currentMessage());
showTime();
}
function currentMessage() {
var message = null;
if (messages.length) {
var now = toTheSecond(new Date());
var start = toTheSecond(new Date(messages[0].start_time));
var end = toTheSecond(new Date(start.getTime() + ( messages[0].text_duration * 1000 )));
if (start <= now) {
if (end <= now) {
// done with the current message...
messages = messages.slice(1);
// ...but check if there's another one ready to go right now
message = currentMessage();
}
else {
message = messages[0];
}
}
}
return message;
}
function toTheSecond(date) {
date.setMilliseconds(0);
return date;
}
function showMessage(message) {
if (message) {
display.textContent = message.text_content;
}
else {
display.textContent = "no messages";
}
}
function showTime() {
time.textContent = new Date().toLocaleString()
}
function getMessages() {
setTimeout(function() {
var now = new Date();
messages.push(
{"text_content":"aaaaa","text_duration":5,"start_time": new Date(now.getTime() + 3000).toISOString()},
{"text_content":"aawwaaaaa","text_duration":5,"start_time": new Date(now.getTime() + 10000).toISOString()},
{"text_content":"bbaawwaaaaa","text_duration":5,"start_time": new Date(now.getTime() + 15000).toISOString()}
);
}, 1000);
}
setInterval(check, 500);
getMessages();
})();
<span id="current-time"></span> <span id="message">Hello there!</span>
(也将代码放入此处,因为我想起了答案中想要的代码,因此可以对其进行控制,但是这里有一个演示:
(Putting the code here as well because I recall SO want code in the answers so it's controlled, but there's a demo here: http://jsfiddle.net/nauzilus/ymp0615g/).
这可能没有达到应有的效率;每次迭代都会设置消息文本,这可能会导致重画/重排.但是,无论如何,再次设置时间戳还是可以的,所以meh:)
This probably isn't as efficient as it could be; the message text is being set every iteration which might cause repaints/reflow. But then again setting the time stamp is going to do that anyway, so meh :)
这篇关于如何在现有代码中将滴答时钟添加到div中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!