Home >Web Front-end >JS Tutorial >Introducing javascript to implement timer countdown
Without further ado, let’s get straight to the code.
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title></head><body> <p> <span class="hour">1</span> <span class="minute">2</span> <span class="second">3</span> </p> <script> var hour = document.querySelector('.hour'); //小时的黑色盒子 var minute = document.querySelector('.minute'); //分钟的黑色盒子 var second = document.querySelector('.second'); //秒数的盒子 var inputTime = +new Date('2021-4-10 23:00:00'); //返回的是用户输入的时间总的毫秒数 // 封装好的计算时间的函数 //先调用一次函数防止开始出现空白 countDown(); //开启定时器 setInterval(countDown,1000); function countDown() { var nowTime = +new Date(); //返回的是当前时间的走毫秒数 var times = (inputTime - nowTime) / 1000; //times是剩余时间的总数 // var d = parseInt(times / 60 / 60 / 24); //天 // d = d < 10 ? '0' + d : d; var h = parseInt(times / 60 / 60 % 24); //时 h = h < 10 ? '0' + h : h; hour.innerHTML = h; //把剩余的小时给小时黑盒子 var m = parseInt(times / 60 % 60); //当前秒 m = m < 10 ? '0' + m : m; minute.innerHTML = m;//把剩余的分钟给盒子 var s =parseInt(times%60);//当前秒 s = s < 10 ? '0' + s : s; second.innerHTML = s;//把剩余的秒数给盒子 // return d + '天' + h + '时' + m + '分' + s + '秒'; } </script></body></html>
A time conversion function is encapsulated here:
function countDown() { var nowTime = +new Date(); //返回的是当前时间的走毫秒数 var times = (inputTime - nowTime) / 1000; //times是剩余时间的总数 var d = parseInt(times / 60 / 60 / 24); //天 d = d < 10 ? '0' + d : d; var h = parseInt(times / 60 / 60 % 24); //时 h = h < 10 ? '0' + h : h; var m = parseInt(times / 60 % 60); //当前秒 m = m < 10 ? '0' + m : m; var s =parseInt(times%60);//当前秒 s = s < 10 ? '0' + s : s; return d + '天' + h + '时' + m + '分' + s + '秒'; }
Related Free learning recommendations: javascript learning tutorial
The above is the detailed content of Introducing javascript to implement timer countdown. For more information, please follow other related articles on the PHP Chinese website!