<!DOCTYPE html> <html lang="zh"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>倒计时</title> <style type="text/css"> *{ margin: 0; padding: 0; } img{ border: none; } .timeplane { width: 125px; height: 40px; line-height: 40px; background-color: #a6baab; border-radius: 20px; float: left; font-size: 20px; font-weight: bold; color: #333; } #timeplane img { width: 28px; margin-top: 4px; margin-left: 20px; margin-right: 10px; display: block; float: left; } </style> </head> <body> <div class="timeplane" id="timeplane"><img src="http://api.touchtao.tech/distich/images/time.png"><span id="livetime">00:00</span></div> <br /> <br /> <br /> <div>自定义倒计时时间,倒计时结束后执行,停止倒计时,倒计时重新执行</div> </body> <script src="http://libs.baidu.com/jquery/1.11.3/jquery.min.js"></script> <script type="text/javascript"> var timestart = 20; //定义倒计时时间; var timestep = -1; var timeID; function timecount() { $("#livetime").html(formatSeconds(timestart)); timestart += timestep; if(timestart < 0){ timestart = 20;//时间; //赋值0 倒计时结束,就变00:00 return false; //倒计时为0时执行xxxx方法 }else{ var endTime = $("#livetime").html(); // console.log(endTime); if(endTime == '00:01'){ setTimeout(function(){ // ******************倒计时结束了 alert("倒计时结束了") },1000); } } timeID=setTimeout("timecount()",1000); } formatSeconds = function(timestart) { var theTime = parseInt(timestart);// 需要转换的时间秒 var theTime1 = 0;// 分 var theTime2 = 0;// 小时 var theTime3 = 0;// 天 if(theTime >= 60) { theTime1 = parseInt(theTime/60); theTime = parseInt(theTime%60); if(theTime1 > 60) { theTime2 = parseInt(theTime1/60); theTime1 = parseInt(theTime1%60); if(theTime2 > 24){ //大于24小时 theTime3 = parseInt(theTime2/24); theTime2 = parseInt(theTime2%24); } } } else { var result = '00:'; if(theTime < 10) { result += '0'+theTime; } else { result += theTime; } return result; } var result = ''; if(theTime > 0){ // 秒 theTime = parseInt(theTime); if(theTime < 10) { theTime = '0'+theTime; } result = ""+theTime; } else { result += "00"; } if(theTime1 > 0) { // 分钟 theTime1 = parseInt(theTime1); if(theTime1 < 10) { theTime1 = '0'+theTime1; } result = ""+theTime1+":"+result; } else { result += "00"; } if(theTime2 > 0) { // 小时 theTime2 = parseInt(theTime2); if(theTime2 < 10) { theTime2 = '0'+theTime2; } result = ""+theTime2+":"+result; } if(theTime3 > 0) { // 天 theTime3 = parseInt(theTime3); result = ""+theTime3+" "+result; } return result; } timecount(); //倒计时开始 setTimeout(function(){ //测试5秒后停止倒计时 // clearTimeout(timeID); //停止倒计时(都可以用) window.clearTimeout(timeID); //停止倒计时(都可以用) timestart = 20; //时间重新赋值 timecount(); //再执行倒计时 },5000); </script> </html>