js 定时器

时间:2023-03-10 01:07:10
js 定时器
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<span id="time1"></span>
<br>
<button id="aStop">第一个停</button><button id="aBegain">第一个开</button>
<br>
<br>
<br>
<div id="time2"></div><button id="bStop">第二个停</button><button id="bBegain">第二个开</button>
</body>
<script type="text/javascript">
function Time(option){
this.father = document.getElementById(option.father);
this.allTime = option.allTime || 0;
this.hours = option.hours || 0;
this.strH = option.strH || "时";
this.mins = option.mins || 0;
this.strM = option.strM || "分";
this.seconds = option.seconds || 0;
this.strS = option.strS || "秒";
this.htmlV = null;
this.t = null;
this.timeStr = null;
this.init();
}
Time.prototype = {
init:function(){
this.mune();
this.setI();
},
mune:function(){
if(this.allTime != 0){
this.hours = Math.floor(this.allTime / (60*60));
this.mins = Math.floor(this.allTime / 60);
this.seconds = this.allTime % 60;
}
},
setI:function(){
var self = this;
this.t = setInterval(function(){
self.father.innerHTML = self.hours +self.strH + self.mins+self.strM + self.seconds +self.strS;
self.allTime = self.hours*60*60 + self.mins *60 +self.seconds;
if(self.allTime == 0){
clearInterval(self.t);
self.father.innerHTML = "时间已经过期"
return;
}
--self.seconds;
if(self.seconds < 0){
self.seconds = 59;
--self.mins;
if(self.mins < 0){
self.mins = 59;
--self.hours
if(self.hours == 0){
self.hours = 0;
}
}
}
if(self.allTime == 0){
clearInterval(self.t);
self.father.innerHTML = "计时结束";
} },1000)
}
}
window.onload = function(){
var a = null; //全局变量
a = new Time({
father:"time1",
allTime:153,
})
var time = null; //保存当前停止的时间\
var stop = false; document.getElementById("aStop").onclick = function(){
clearInterval(a.t);
stop = true;
console.log(a.allTime) //停止时,所剩的总秒数
time = a.allTime;
}
document.getElementById("aBegain").onclick = function(){
console.log(stop)
if(!stop){ //判断当前倒计时是否停止,如果没停止则不执行
return;
}
if(a.allTime <= 0){
return;
}
a = new Time({ //重新给启动定时器
father:"time1",
allTime:time,
})
stop = false;
}
/*------------a----f分割线-----b---------------*/ var b = null;
b = new Time({
father:"time2",
hours:1, //尽量传总秒数
mins:0,
seconds:2,
})
var bTime = null;
var Bstop = false;
document.getElementById("bStop").onclick = function(){
clearInterval(b.t)
Bstop = true;
bTime = b.allTime;
}
document.getElementById("bBegain").onclick = function(){
if(!Bstop){
return;
}
if(a.allTime <= 0){
return;
}
b = new Time({ //重新给启动定时器
father:"time2",
allTime:bTime,
})
Bstop = false;
}
}
</script>
</html>