简体   繁体   English

实时时钟JavaScript从我的自定义时间开始

[英]Live clock javascript starts from my custom time

I was trying to create a live/dynamic clock is based on my custom time instead of system time. 我试图根据我的自定义时间(而不是系统时间)创建实时/动态时钟。

There are many scripts, but I couldn't find the clock starts from my custom time. 脚本很多,但是我找不到自定义时间开始的时钟。

Here is an example that I'm trying to modify. 这是我要修改的示例。 The problem is the seconds doesn't change, and it looks like I need to use ajax. 问题是秒数没有变化,看起来我需要使用ajax。 Is there any way to do it without ajax? 没有ajax,有什么方法可以做到吗? If not, help me to do it using ajax!!! 如果没有,请帮助我使用ajax来做!!! The reason I don't like ajax method is that another page should be called and refreshed, so it will eat server ram. 我不喜欢ajax方法的原因是应该调用并刷新另一个页面,这样它将占用服务器内存。

ex) http://www.javascriptkit.com/script/cut2.shtml 例如) http://www.javascriptkit.com/script/cut2.shtml

Before: 之前:

<script> 
function show(){ 
var Digital=new Date() 
var hours=Digital.getHours() 
var minutes=Digital.getMinutes() 
var seconds=Digital.getSeconds() 
... 
... 

After: 后:

<script> 
function show(){ 
var Digital=new Date() 
var hours=<?php echo $hr; ?>; 
var minutes=<?php echo $min; ?>; 
var seconds=<?php echo $sec; ?>; 
... 
... 

The reason your clock isn't moving is because it's using the hours, minutes and seconds values set by the server when the page was originally rendered, as opposed to a fresh new Date() instance created each time show() is called. 您的时钟不动的原因是因为它使用的是服务器在最初呈现页面时设置的小时,分​​钟和秒值,而不是每次调用show()都会创建一个新的Date()实例。 You'll want to take advantage of JavaScript's built in Date object to create an accurate clock, as setTimeout isn't known for its accuracy and building your own clock would be a hassle (imaging having to worry about leaps years and daylight savings and stuff!). 您将要利用JavaScript的内置Date对象来创建准确的时钟,因为setTimeout以其准确性而闻名,并且构建自己的时钟会很麻烦(想像一下要花很多Date才能节省时间和日光节约时间) !)。

What I'd recommend is to adjust the clock value each time show() is called using the difference between your custom time and the real time. 我建议每次使用您的自定义时间和实时时间之间的差异来调整每次调用show()时的时钟值。 For example, if your custom time is 30 minutes behind the real time, you can call: 例如,如果您的自定义时间比实时时间晚30分钟,则可以致电:

function show() {
   var Digital=new Date();
   Digital.setMinutes(Digital.getMinutes() - 30); // Rewind 30 minutes
   var hours=Digital.getHours()
   var minutes=Digital.getMinutes()
   var seconds=Digital.getSeconds()
   // ..
}

Fiddle 小提琴

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM