定时器清除不了
倒数到0的时候还在后台倒计时,根本停不下来,这样浏览器很容易崩溃吧,分别试了setTimeout和setInterval,定时器写里面外面都清不掉,是我写错了吗?望大神小神过来搭救~
<!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>团购——限时抢</title> <!-- <link rel="stylesheet" href="style.css" /> --> </head> <body> <div class="content3"> <div class="time">还剩 <span id="LeftTime"></span></div> </div> <script> window.onload=function(){ FreshTime() // var sh; // sh=setInterval(FreshTime,500); // sh=setTimeout(FreshTime,500); 不能写函数外面,只调用一次!! } function FreshTime() { var endtime=new Date("2017/1/7,10:31:40");//结束时间 var nowtime = new Date();//当前时间 var lefttime =parseInt((endtime.getTime() - nowtime.getTime())/1000); var d = parseInt(lefttime/(24*60*60)); //把总共的秒数除以一天的秒数 var h = parseInt(lefttime/(60*60)%24); //取模得出当前剩下的小时数 var m = parseInt(lefttime/60%60); var s = parseInt(lefttime%60); document.getElementById("LeftTime").innerHTML=d+"天"+h+"小时"+m+"分"+s+"秒"; if(lefttime<=0){ document.getElementById("LeftTime").innerHTML="团购已结束"; // clearTimeout(sh); clearInterval(sh); } // sh=setTimeout(FreshTime,500); sh=setInterval(FreshTime,500); console.log(d+"天"+h+"小时"+m+"分"+s+"秒"); //注意控制台的变化 } </script> </body> </html>