jquery - 如何实现 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);
不幸的是,这并没有让时间滴答作响,让我想知道为什么。我想知道我做错了什么。
解决方案
将所有代码放入一个函数中,然后每隔一秒使用 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>
推荐阅读
- c++ - 函数指针类型不能用于函数原型
- architecture - 分析 API、新的微服务或与现有 API 集成?
- json - 如何从 objectmapper 获取具有漂亮打印和 json 视图的对象编写器?
- javascript - 属性或方法“cancella”未在实例上定义,但在渲染期间引用
- django - 如何在 Django 中以编程方式登录?
- dns - 在没有重定向的情况下在 Cloudfront 中指定源路径
- reactjs - 如何在点击事件的下钻图中上传/设置动态(使用 axios)数据?
- javascript - 尝试在控制台中记录函数时未定义
- c# - EntityFramework 中的 SaveChanges() 不保存更改。显示“函数评估需要所有线程运行”
- c# - 如何将 Database First Entity Framework 4 升级到 6