话不多说上代码
首先设置style样式和div盒子存放按钮和显示时间
div{
width: 300px;
height:200px;
background: #333;
margin:50px auto;
color: #fff;
text-align: center;
line-height: 100px;
}
<div>
<span id="hour">00</span> :
<span id="min">00</span> :
<span id="sencond">0</span>
<br>
<input type="button" value="Start" id="start">
<input type="button" value="Stop" id="stop">
<input type="button" value="Reset" id="reset">
</div>`
js代码
let startTime;//定义点击start的时间
let dis ;//定义
let b=null;//定时器id
let last=0; //定义暂停的时间戳
let last2=0;//定义暂停的时间
let h = document.getElementById("hour");
let m = document.getElementById("min");
let s=document.getElementById("sencond");
let oStart = document.getElementById("start");
let oStop = document.getElementById("stop");
let oReset = document.getElementById("reset");
function jishi(){
dis=Date.now()-startTime-last2;//现在的时间-点击开始的时间-暂停的时间
h.innerHTML =a(Math.floor((dis/1000/3600)%24));
m.innerHTML = a(Math.floor((dis/1000/60)%60));
s.innerHTML=a(Math.floor((dis/1000)%60));
function a(n){
if (n<10){
return "0" + n;}
else{
return n;}
}
//让时间是两位数
}
oReset.onclick = function(){
history.go();
}
//点击reset
function d(){b=setInterval(jishi,100)}
function c(){
start.setAttribute('disabled','disabled');
//禁用按钮
startTime = Date.now()
d()
}
oStart.addEventListener('click', c)
//点击start
oStop.onclick=function(){
if(oStop.value=="Stop")
{
last=Date.now();//点暂停的时间戳
oStop.value="continue"
clearInterval(b);}
else if(oStop.value=="continue")
{oStop.value="Stop"
last2+=Date.now()-last;//暂停的总时间
d();
}
}
</script>