JavaScript 实现动态时钟定时器完整代码
作者:小括号时间:2026-10-23 17:00:25浏览:621
本文提供使用 JavaScript 实现动态时钟定时器的完整代码示例。通过获取当前时间对象并提取年、月、日、时、分、秒等属性,结合 setInterval 定时器实现页面时间的实时刷新与显示,适用于前端基础教学与简单时钟功能开发。
JavaScript 实现动态时钟定时器完整代码
本文分享了一段使用 JavaScript 实现时钟定时器的具体代码,供读者参考学习。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>时钟</title>
<script type="text/javascript">
function showClock(){
// 1. 获取当前时间
var time = new Date();
// document.write(time);
var year = time.getFullYear();
// document.write(year);
var month = time.getMonth() + 1;
// document.write(month);
var day = time.getDate();
// var day1 = time.getDay();
// document.write(day1);
var hours = time.getHours();
// document.write(hours);
var minutes = time.getMinutes();
// document.write(minutes);
var seconds = time.getSeconds();
document.getElementById("clock").innerHTML = year+"-"+month+"-"+day+" "
+hours+":"+minutes+":"+seconds;
}
var flag = true;
var id;
function runClock(){
var btn = document.getElementById("btn");
if(flag){
// 计时操作
id = setInterval("showClock()",1000);
flag = false;
btn.innerHTML = "停止";
}else{
// 停止计时操作
clearInterval(id);
flag = true;
btn.innerHTML = "动起来";
}
}
</script>
</head>
<body>
<button οnclick="showClock()">点击显示时钟</button>
<div id="clock">
</div>
<button id="btn" οnclick="runClock()">动起来</button>
</body>
</html>

以上内容为本文的全部代码示例,希望能为读者的学习带来帮助,也欢迎大家继续支持本站。
作者最新文章
JS语法错误会阻止加载吗?区分SyntaxError与资源加载失败
2026-11-05 16:08:46
JavaScript常见SyntaxError语法错误排查与修复方法
2026-11-05 13:58:44
JS中slice、substring和substr截取字符串的区别
2026-11-05 13:43:47
JS 转 TS 手动迁移最佳实践:从配置 tsconfig 到消除 any 类型
2026-11-05 11:53:32
为什么JS数组push后得到的是数字而不是数组?
2026-11-05 09:59:18
