2016-06-02 定时器 倒计时
1.未做封装的代码很是混乱
<style> input{width: 300px;height:20px;margin: 10px} #btn{width: 150px;height: 30px;margin-left: 65px} </style> <script> window.onload=function(){ var inputs = document.getElementsByTagName('input'); var timer=null; var seconds=null; var currentDate=null; var str=''; var targetDate = new Date(inputs[0].value);//目标时间 固定不变的 inputs[2].onclick=function(){ clearInterval(timer); timer =setInterval(function(){ if(seconds>=0){ currentDate =new Date();//当前时间 seconds = Math.floor((targetDate-currentDate)/1000);//毫秒转换成s str=Math.floor(seconds/86400)+'天'+Math.floor(seconds%86400/3600)+'时'+Math.floor(seconds%86400%3600/60)+'分'+seconds%60+' 秒'; inputs[1].value=str; }else{ clearInterval(timer); } },1000); } } </script> </head> <body> 距 离:<input type="text" value="June 7,2016 00:00:00"><br> 还剩下:<input type="text"><br> <input id="btn" type="button" value="开始倒计"> </body>
2.封装后的代码,更快更好
<script> window.onload=function(){ var inputs = document.getElementsByTagName('input'); var timer=null; var delta=null; var currentDate=null; var str=''; var targetDate = new Date(inputs[0].value);//目标时间 固定不变的 inputs[2].onclick=function(){ firstGet();//否则页面出现卡顿,这个是上来就显示时间信息到input框中 clearInterval(timer); timer =setInterval(firstGet,1000); function firstGet(){ if(delta>=0){ currentDate =new Date();//当前时间 delta =targetDate-currentDate; str=getDayHourMinSecondByMs(delta); inputs[1].value=str; }else{ clearInterval(timer); } } } } function getDayHourMinSecondByMs(ms){ var seconds = Math.floor(ms/1000);//毫秒转换成s return Math.floor(seconds/86400)+'天'+Math.floor(seconds%86400/3600)+'时'+Math.floor(seconds%86400%3600/60)+'分'+seconds%60+' 秒'; } </script>