最近项目中用到倒计时与计时的功能,代码如下:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>倒计时与从0计时</title> </head> <body> <h1>从0开始计时</h1> <div id="divTime"></div> <h1>倒计时30秒</h1> <div id="last">加载中</div> <script src="jquery.min.js"></script> <script type="text/javascript"> //从0计时 var timeIndex = 0; function setTime(){ var hour = parseInt(timeIndex / 3600); var minutes = parseInt((timeIndex % 3600) / 60); var seconds = parseInt(timeIndex % 60); hour = hour < 10 ? "0" + hour : hour; minutes = minutes < 10 ? "0" + minutes : minutes; seconds = seconds < 10 ? "0" + seconds : seconds; $("#divTime").html(hour + ":" + minutes + ":" + seconds); timeIndex++; } setTime(); setInterval(setTime, 1000); //倒计时 function dao(allsecont){ console.log(allsecont) var minute_time = Math.floor(allsecont/60000); console.log(minute_time) var x = minute_time, interval; var d = new Date("1111/1/1,0:" + x + ":0"); interval = setInterval(function() { var m = d.getMinutes(); var s = d.getSeconds(); m = m < 10 ? "0" + m : m; s = s < 10 ? "0" + s : s; $('#last').html(m + ":" + s); if (m == 0 && s == 0) { clearInterval(interval); return; } d.setSeconds(s - 1); }, 1000); } dao(1800000) //单位毫秒 </script> </body> </html>