We often need to set a countdown on the page at work, so do you know how to write JS countdown code? This article will share with you the simplest JS countdown code and the detailed countdown JS code ideas. It has certain reference value and interested friends can take a look.
Example: Set a deadline and display the remaining time. For example, Double Eleven is coming soon, and merchants are holding activities. They can use JS countdown to show how long it is until the end of the activity. The specific code is as follows:
HTML part:
<body onload = "countTime()"> <div> <span id="day"></span> <span id="hour"></span> <span id="minute"></span> <span id="second"></span> </div> </body>
Give four tags to display the remaining days, hours, minutes and seconds
JavaScript part:
<script type="text/javascript"> function countTime() { //获取当前时间 var date = new Date(); var now = date.getTime(); //设置截止时间 var endDate = new Date("2018-10-31 0:0:0"); var end = endDate.getTime(); //获取截止时间和当前时间的时间差 var leftTime = end-now; //定义变量 d,h,m,s分别保存天数,小时,分钟,秒 var d,h,m,s; //判断剩余天数,时,分,秒 if (leftTime>=0) { d = Math.floor(leftTime/1000/60/60/24); h = Math.floor(leftTime/1000/60/60%24); m = Math.floor(leftTime/1000/60%60); s = Math.floor(leftTime/1000%60); } //将时间赋值到div中 document.getElementById("day").innerHTML = d+"天"; document.getElementById("hour").innerHTML = h+"时"; document.getElementById("minute").innerHTML = m+"分"; document.getElementById("second").innerHTML = s+"秒"; //递归每秒调用countTime方法,显示动态时间效果 setTimeout(countTime,1000); } </script>
Countdown JS code ideas:
1. Use date = new Date() to get the current time
2. Set the deadline endDate = new Date( "2018-10-31 0:0:0")
3. Get the time difference leftTime = end-now
4. Define variables d, h, m, s and use the if function to judge The remaining days, hours, minutes and seconds
5. Use innerHTML to assign the time to the div
6. Recursively call the countTime function every second to display the dynamic time effect
Effect As shown in the picture:
The above has shared a simple JS countdown code with you, and explained the idea of the JS countdown code in detail. You can use it directly at work. Compare It’s simple. Beginners can try it themselves and see if they can achieve the countdown effect. I hope this article will be helpful to you!
Recommended related video tutorials: JavaScript video tutorial
The above is the detailed content of Share the simplest JavaScript countdown code (complete code attached). For more information, please follow other related articles on the PHP Chinese website!