一个页面显示多个倒计时,每个对应的项目需要显示倒计时的控件添加一个计时器,倒计时生成一个实例:var time = new Timer()如下代码:
/***startime 应该是毫秒数
*
*/
var Alarm = function (startime, endtime, countFunc, endFunc) {
this.time = Math.floor((endtime - startime) / 1000) //时间
this.countFunc = countFunc //计时函数
this.endFunc = endFunc //结束函数
this.flag = 't' + Date.parse(new Date()) //
}
Alarm.prototype.start = function () {
var self = this
self.flag = setInterval(function () {
if (self.time < 0) {
clearInterval(self.flag)
self.endFunc()
console.log('计时结束')
} else {
var minute, hour, day, second
day = Math.floor(self.time / 60 / 60 / 24) < 10 ? '0' + Math.floor(self.time / 60 / 60 / 24) : Math.floor(self.time / 60 / 60 / 24)
hour = Math.floor(self.time / 60 / 60 % 24) < 10 ? '0' + Math.floor(self.time / 60 / 60 % 24) : Math.floor(self.time / 60 / 60 % 24)
minute = Math.floor(self.time / 60 % 60) < 10 ? '0' + Math.floor(self.time / 60 % 60) : Math.floor(self.time / 60 % 60)
second = Math.floor(self.time % 60) < 10 ? '0' + Math.floor(self.time % 60) : Math.floor(self.time % 60)
//倒计时执行函数
self.countFunc(second, minute, hour, day)
self.time--
}
}, 1000)
}
<html><body>
<div id="RemainH"></div>
<div id="RemainM"></div>
<div id="RemainS"></div>
</body>
<script language="JavaScript">
//var runtimes = 0
function GetRTime(lefttime,runtimes){
var nMS = lefttime*1000-runtimes*1000
var nH=Math.floor(nMS/(1000*60*60))%24
var nM=Math.floor(nMS/(1000*60)) % 60
var nS=Math.floor(nMS/1000) % 60
if(nS == 0 &&nH == 0 &&nM == 0){
alert('活动开始')
return false
}
document.getElementById("RemainH").innerHTML=(nH)
document.getElementById("RemainM").innerHTML=(nM)
document.getElementById("RemainS").innerHTML=(nS)
if(nMS>5*59*1000&&nMS<=5*60*1000){
alert("还有最后五分钟!")
}
runtimes++
//setTimeout("GetRTime()",1000)
setTimeout(function(){
GetRTime(lefttime,runtimes)
},1000)
}
window.onload=GetRTime(30000,0)
</script>
</html>
JS定时器:<script>
var myVar = setInterval(myTimer, 1000)
function myTimer() {
var d = new Date()
document.getElementById("demo").innerHTML = d.toLocaleTimeString()
}
</script>