最近学习JavaScript的计时器功能,做了一个小案例,
在此记录一下,需要的童鞋可以看一下,代码的缺点
是小时数部分计时样式没有做出来完整的显示,望海涵。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
</head>
<body>
<div></div>
<button>开始</button>
<button>停止</button>
<button>重置</button>
<script>
</script>
<script>
var s = 0;
var f = 0;
var h = 0;
let oDiv = document.querySelector('div');
let oBton1 = document.querySelectorAll('button')[0];
let oBton2 = document.querySelectorAll('button')[1];
let oBton3 = document.querySelectorAll('button')[2];
chongzhi();
function chongzhi() {
oDiv.innerHTML = '0' + h + ':' + 0 + f + ':' + 0 + s;
}
oBton1.addEventListener('click', function () {
let int = setInterval(function () {
s += 1;
if (s === 60) {
s = 0;
f += 1;
if (f === 60) {
h += 1;
}
}
if (s < 10 && f < 10) {
oDiv.innerHTML = '0' + h + ':' + 0 + f + ':' + 0 + s;
} else if (s < 10 && f >= 10) {
oDiv.innerHTML = '0' + h + ':' + f + ':' + 0 + s;
} else if (s >= 10 && f < 10) {
oDiv.innerHTML = '0' + h + ':' + 0 + f + ':' + s;
} else if (s >= 10 && f >= 10) {
oDiv.innerHTML = '0' + h + ':' + f + ':' + s;
}
}, 1000);
oBton2.addEventListener('click', function () {
clearInterval(int);
});
oBton3.addEventListener('click', function () {
oDiv.innerHTML = 0 + '0' + ':' + 0 + 0 + ':' + 0 + 0;
});
});
</script>
</body>
</html>