废话不多说了,直接给大家贴代码了。具体代码如下所示:
其实这倒计时之前有接触过很多,只是用的都是别人的源码。
应项目需求,终于认真一回,把一个自己看似很简单的问题,终于耗上了跨度一个星期的时间,才弄出来。
源码直接复制黏贴可用。
冗余版+简化版。
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title></title>
</head> <body>
<script type="text/javascript">
var createtime = '2016-11-14 10:20:00';//开始时间
var limittimes = 10;//时间长度
// 倒计时 入口
countdowns = window.setinterval(function(){
var arr = cutdoowns(limittimes,createtime);
document.write(formatdate(arr[0])+':'+formatdate(arr[1])+':'+formatdate(arr[2])+'</br>');
if(arr[2]){
document.write('时间到!');
}
},1000);
/*
s,10分钟后的具体日期:
date,开始时间
然后转化成毫秒比较,所得的差值化成分秒,就是倒计时的分秒。
*/
function cutdoowns(s,date){
console.log('');
var flag = false;
var arr = [];//arr[0]:分,arr[1]:秒,arr[2]:返回boolean
var now = new date();//当前时间
var now1 = new date(date);//开始时间
console.log('开始时间 now1: '+now1);
now1.setminutes(now1.getminutes()+s);//10分钟后的时间
console.log('当前时间 now :'+now);
console.log('10分钟时 now1:'+now1);
// 转化成年月日 时分秒 格式
var n = now.getfullyear()+'/'+(now.getmonth()+1)+'/'+now.getday()+' '+now.gethours()+':'+now.getminutes()+':'+now.getseconds();
var n1 = now1.getfullyear()+'/'+(now1.getmonth()+1)+'/'+now1.getday()+' '+now1.gethours()+':'+now1.getminutes()+':'+now1.getseconds();
// 日期转化成毫秒
var time1 = (new date(n)).gettime();
var time2 = (new date(n1)).gettime();
// 毫秒转日期格式
var time11 = new date(time1);
var time21 = new date(time2);
console.log('当前时间:'+n+',转化成毫秒:'+time1+',time11:'+time11);
console.log('10分钟时:'+n1+',转化成毫秒:'+time2+',time21:'+time21);
var surplussec = time2-time1;//距离解锁剩余毫秒
if(surplussec<=0){
clearinterval(countdowns);
flag = true;
return arr = [00,00,flag];
}
var minute = math.floor(surplussec/1000/60);//分钟
var second = math.floor((surplussec-minute*60*1000)/1000);//剩余秒数
console.log('剩余时间,minute: '+minute+',second: '+second+',surplussec:'+surplussec);
// var second = math.round(surplustimes);//秒数
console.log('剩余时间,minute: '+minute+',second: '+second+',surplussec:'+surplussec);
arr = [minute,second,flag];
return arr;
}
//格式化日期:把单字符转成双字符
function formatdate(n){
n = n.tostring();
// console.log(n);
if(n.length<=1){
n = '0'+n;
}
// console.log(n);
return n;
}
</script>
</body>
</html>
简化版本:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>打开调试工具,看效果!</title>
</head>
<body>
<script type="text/javascript">
/*
打开调试工具,看效果!
思路:
1.设置一个倒计时的时间长度;
2.设置开始时间和当前时间;
3.结束时间是 开始时间+倒计时间;
4.结束毫秒-开始毫秒=剩余倒计时间。
*/
// 准备
var countdownminute = 10;//10分钟倒计时
var starttimes = new date('2016-11-16 15:55');//开始时间 new date('2016-11-16 15:21');
var endtimes = new date(starttimes.setminutes(starttimes.getminutes()+countdownminute));//结束时间
var curtimes = new date();//当前时间
var surplustimes = endtimes.gettime()/1000 - curtimes.gettime()/1000;//结束毫秒-开始毫秒=剩余倒计时间
// 进入倒计时
countdowns = window.setinterval(function(){
surplustimes--;
var minu = math.floor(surplustimes/60);
var secd = math.round(surplustimes%60);
console.log(minu+':'+secd);
if(surplustimes<=0){
console.log('时间到!');
clearinterval(countdowns);
}
},1000);
</script>
</body>
</html>