【问题标题】:How to implement setInterval to update a clock every second?如何实现 setInterval 每秒更新一个时钟?
【发布时间】:2020-11-06 02:04:06
【问题描述】:

我正在使用以下代码在我的网站上显示当前时间。

let currentDateTime = new Date();

hours = ('0'+currentDateTime.getHours()).slice(-2);
mins = ('0'+currentDateTime.getMinutes()).slice(-2);

let formattedTime = hours + ":" + mins;

$('#time').html(formattedTime);

这会产生时间。然而;时间没有运行。我希望通过设置每秒更新时间的间隔来使这个时钟运行。我尝试添加.setInterval(1000); 如下:

let currentDateTime = new Date();

hours = ('0'+currentDateTime.getHours()).slice(-2);
mins = ('0'+currentDateTime.getMinutes()).slice(-2);

let formattedTime = hours + ":" + mins;

$('#time').html(formattedTime).setInterval(1000);

不幸的是,这并没有让时间流逝,让我想知道为什么。我想知道我做错了什么。

【问题讨论】:

  • 什么是更新时间?
  • 1) setInterval() 不是 jQuery 方法。 2) setInterval() 需要回调函数。建议你仔细研究文档~developer.mozilla.org/en-US/docs/Web/API/…
  • 我很抱歉菲尔,我是一个新手,并没有意识到这一点。感谢您对我的教育,并会阅读。
  • 你好,看我的回答:)

标签: jquery date time


【解决方案1】:

将所有代码放入一个函数中,然后每隔一秒使用 setInterval 调用它

function updateTime () {
  let currentDateTime = new Date();

  hours = ('0'+currentDateTime.getHours()).slice(-2);
  mins = ('0'+currentDateTime.getMinutes()).slice(-2);

  let formattedTime = hours + ":" + mins;

  $('#time').html(formattedTime)
}

setInterval(updateTime, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="time"></div>

【讨论】:

    【解决方案2】:

    // HTML element where the time will be displayed
    var clock = $('#clock');
    
    // Returns an object with the time, minutes and seconds
    function time() {
      // Object Instance Date
      var date = new Date();
      return {
        hours: date.getHours(),
        minutes: date.getMinutes(),
        seconds: date.getSeconds(),
      }
    }
    
    // Execute the time function every second
    setInterval(function() {
      // We store the object that returns the time function
      var date = time();
      // We use the .text method to display the time
      clock.text(date.hours + ':' + date.minutes + ':' + date.seconds)
    }, 1000)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <h1 id="clock"></h1>

    【讨论】:

    • 您缺少数字上的零填充
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-25
    • 2022-11-30
    • 1970-01-01
    • 2021-11-08
    • 1970-01-01
    相关资源
    最近更新 更多