倒计时 定时器
代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <div id="box"></div> <script> /* 未来时间 - 现在时间 = 等待时间 时间戳(ms) */ setInterval(auto,1000); function auto(){ var currentTime = new Date(); // 当前时间 var targetTime = new Date(2020,9,1,0,0,0); // 未来时间 var waitTime = (targetTime - currentTime)/1000; // 秒数 // console.log(waitTime); // 一天 24*60*60 = 86400 s // 一小时 60*60 = 3600 s // 一分钟 60s var day = parseInt(waitTime / 86400); var hours = parseInt((waitTime % 86400)/3600); var minutes = parseInt((waitTime % 86400)%3600 / 60); var seconds = parseInt((waitTime % 86400)%3600 % 60); var box = document.getElementById('box'); box.innerHTML = '距离2020年国庆节还有:' + day + '天' + addZero(hours) +'小时' + addZero(minutes) + '分' + addZero(seconds) + '秒钟'; } auto(); // 加0封装 function addZero(time) { return time = time >=10? time:'0'+time } </script> </body> </html>