This article mainly shares with you the JS implementation of obtaining time and setting countdown code, hoping to help everyone.
Just take notes and record them, mainly using Date
and setInterval
The setting of the first countdown:
<script type="text/javascript"> var timeBox = document.querySelector("#time"); function countdown(){ var nowTime = new Date(); var targetTime = new Date("2018/2/27 15:44:15"); var spanTime = targetTime-nowTime; if(spanTime <=0){ timeBox.innerHTML="立即抢购"; clearInterval(countdown); }else{ var hours = Math.floor(spanTime/(1000*60*60)); spanTime-=hours*60*60*1000; var minute = Math.floor(spanTime/(1000*60)); spanTime-=minute*60*1000; var second = Math.floor(spanTime/1000); hours<10 ? hours='0'+hours : hours; minute<10 ? minute='0'+minute : minute; second<10 ? second='0'+second : second; timeBox.innerHTML=hours+':'+minute+':'+second; } } var timer = window.setInterval(countdown,1000); </script>
The second one , display the current date:
<script type="text/javascript"> var timeBox = document.querySelector("#time"); function countdown(){ var date = new Date(); var hours = date.getHours(); var minute = date.getMinutes(); var second = date.getSeconds(); hours =checkTime(hours); minute =checkTime(minute); second =checkTime(second); timeBox.innerHTML = hours+':'+minute+':'+second; } // 检测时间数字是否小于10,在小于10的数字前加一个‘0’ function checkTime(i){ i<10 ? i="0"+i :i; return i; } var timer = window.setInterval(countdown,1000); </script>
Related recommendations:
JS method of obtaining time function and extension function
JS obtain Time method_javascript skills
js anti-refresh countdown code js countdown code
The above is the detailed content of JS implementation of obtaining time and setting countdown code sharing. For more information, please follow other related articles on the PHP Chinese website!