<head>
<meta charset="UTF-8">
<title>5.定时器</title>
</head>
<body>
<div id="show">0</div>
<hr>
<div>
<input type="button" value="开始" onclick="toStart()">
<input type="button" value="暂停" onclick="toPause()">
<input type="button" value="清零" onclick="toClear()">
</div>
<hr>
<div id="clock"></div>
</body>
<script>
showClock();
setInterval(showClock, 10);
function showClock() {
//获取系统当前时间
let now = new Date();
//提取具体时间数据
let year = now.getFullYear()
, month = now.getMonth() + 1
, date = now.getDate()
, hour = now.getHours()
, min = now.getMinutes()
, sec = now.getSeconds()
, mill = now.getMilliseconds();
let msg = year + "-" + month + "-" + date + " " + hour + ":" + min + ":" + sec + "." + mill;
document.getElementById("clock").innerHTML = msg;
}
/************************************************************************************/
let timmer; //定时器对象
function toClear() {
toPause();
document.getElementById("show").innerHTML = 0;
}
function toPause() {
clearInterval(timmer);
timmer = null;
}
function toStart() {
//判断, timmer是否为null
if (!timmer){
timmer = setInterval(function () {
//获取当前的数据
let currNum = document.getElementById("show").innerHTML;
//+1
currNum++;
//判断
if (currNum == 10){
toPause();
}
//显示
document.getElementById("show").innerHTML = currNum;
}, 100);
}
}
</script>