我这里用一个id为countdown的隐藏input标签输入倒计时时长(value值,单位秒),用id分别为hour、mini、sec的三个标签记录时、分、秒
html部分如下:
<input type="hidden" id="countdown" value="1000000" />
剩余时间:<span id="hour">11</span>小时<span id="mini">11</span>分<span id="sec">11</span>秒
jq部分如下(记得载入jq库):
<script type="text/javascript">
function function_exists(a){if(typeof a=='string'){return(typeof window[a]=='function')}else{return(a instanceof Function)}}
var countdown = function(id, total, callback) {
if (total <= 0) {
function_exists(callback) &&callback.call(callback)
return
}
var start_hours = parseInt(total / (60 * 60 * 1000), 10)
var start_minutes = parseInt((total - start_hours * 60 * 60 * 1000) / (60 * 1000), 10)
var start_sec = parseInt(((total - start_hours * 60 * 60 * 1000) - start_minutes * 60 * 1000) / 1000)
$("#sec").html(start_sec <10 ? '0' + start_sec: start_sec)
$("#mini").html(start_minutes <10 ? '0' + start_minutes: start_minutes)
$("#hour").html(start_hours <10 ? '0' + start_hours: start_hours)
total = total - 100
var self = this
setTimeout(function() {
self.countdown(id, total, callback)
},
100)
}
var obj = {
sec: $("#sec"),
mini: $("#mini"),
hour: $("#hour")
}
function run_countdown()
{
if( $('#countdown').size() )
{
countdown(obj, parseInt($('#countdown').val() * 1000), function()
{
$("#sec").html('00')
$("#mini").html('00')
$("#hour").html('00')
})
}
}
$(function(){
run_countdown()
})
</script>
var t=60var a=setInterval(daojishi,1000)//1000毫秒
function daojishi(){
t--
//刷新时间显示
if(t==0){
clearInterval(a)
//倒计时结束
}
}
var timer = 60var timerObj = setInterval(function(){
if(timer == 0){
alert('时间到了')
clearInterval(timerObj)
}
timer--
},1000)
这个是每一秒执行一次,你可以设置一个外部变量 设为倒计时的次数,每次执行的时候减一,当等于0,就说明时间到了