原生JS实现秒表功能
前言
秒表功能在某些业务场景中还是很常见的,在这里用原生写了一个供参考
一、先看效果?好的
二、直接上代码?OK
1.完整html代码如下
代码如下:
<!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>Timer</title>
</head>
<body>
<h1><span class="minute">00</span>:<span class="second">00</span>:<span class="ms">00</span></h1>
<button>暂停/开始</button>
<script>
let M = document.querySelector('.minute');
let S = document.querySelector('.second');
let MS = document.querySelector('.ms');
let btn = document.querySelector('button');
let minute = 0, second = 0, ms = 0, start = true;
let timing = function(){
ms ++;
if(ms === 100){
ms = 0;
second ++;
S.innerText = second < 10 ? '0'+second : second;
}
if(second === 60){
second = 0;
minute ++;
M.innerText = minute < 10 ? '0'+minute : minute;
}
MS.innerText = ms < 10 ? '0'+ms : ms;
}
let timer = setInterval(timing, 10);
btn.onclick = function () {
start = !start;
if (start) {
timer = setInterval(timing, 10);
}else{
clearInterval(timer);
}
}
</script>
</body>
</html>
总结
其实就是简单的使用到了js中的setInterval()定时器,对应到毫秒和秒增加到一定的数量的时候进行‘秒’和‘分’的累加即可。