简体   繁体   English

如何使我的Javascript Clock处于“活动”状态?

[英]How do I make my Javascript Clock 'live'?

I would like assistance on making this clock I created in Javascript/HTML update in real-time. 我需要实时更新我用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>

Any help would be appreciated. 任何帮助,将不胜感激。

You should create an interval timer and just call your timer function every X milliseconds, as you are displaying millisecond precision you might want to keep this low like 100ms. 您应该创建一个间隔计时器,并每隔X毫秒调用一次计时器函数,因为要显示毫秒精度,您可能希望将其保持在100ms之内。 I suggest using setInterval for this. 我建议为此使用setInterval Just put this in your script block: 只需将其放在您的脚本块中:

setInterval(timer, 100);

Here is a full example: 这是一个完整的示例:

 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); 
 <div id="txt"></div> 

Use the setTimeout function (see window.setTimeout ) 使用setTimeout函数(请参见window.setTimeout

In your case: Call the timer function and add 您的情况:调用计时器函数并添加

window.setTimeout(timer, 50);

at the very end of the function. 在功能的最后。

Example: 例:

 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> 

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

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