首页 > 解决方案 > 如何实现 setInterval 每秒更新一个时钟?

问题描述

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

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);

不幸的是,这并没有让时间滴答作响,让我想知道为什么。我想知道我做错了什么。

标签: jquerydatetime

解决方案


将所有代码放入一个函数中,然后每隔一秒使用 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>


推荐阅读