Let’s take a look at the countdown effect:
Code:
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>Countdown function</title> <script> var timer=(function(){ return function (json){ if(json.currentTime){ var now=new Date(); var year=now.getFullYear();//Return year (4 digits) var month=now.getMonth()+1;//Return month (0-11, so +1) var day=now.getDate();//Return a certain day (1-31) var h=now.getHours();//Return hour (0-23) var m=now.getMinutes();//Return minutes (0-59) var s=now.getSeconds();//Return seconds (0-59) //Replenish O m=m<10?'0'+m:m; s=s<10?'0'+s:s; var weekday=['Sunday','Monday','Tuesday','Thursday','Friday','Saturday']; document.getElementById(json.objId).innerHTML=year+'Year'+month+'month'+day'+day'+weekday[now.getDay()]+' '+h+':'+m+':'+s; setTimeout(function(){timer(json)},1000); }else{ var endtime=new Date(json.endtime);//end time var nowtime = new Date();//current time var lefttime=parseInt((endtime.getTime()-nowtime.getTime())/1000); //calculate the number of seconds of difference//24 hours a day, one hour, 60 minutes, one minute, 60 seconds d=parseInt(lefttime/3600/24); h=parseInt((lefttime/3600)%24); m=parseInt((lefttime/60)%60); s=parseInt(lefttime%60); document.getElementById(json.objId).innerHTML=d+"day"+h+"hour"+m+"minute"+s+"seconds"; if(lefttime>0){setTimeout(function(){timer(json)},1000);} } } } } })() window.onload=function(){ timer({ currentTime:true, objId:'thisTime' }) timer({ objId:'countDown', endtime:"2016/9/1,18:00" }) } </script></head><body> <b>Current time:</b> <span id="thisTime"></span><br/><br/> <b>There is still 18:00 from 2016/9/1:</b> <span id="countDown"></span></body></html>Note:
1. There are two functions: the current time and the countdown, and the parameters with different
2. Mainly use the data returned by js. Pay attention to the month, day, hour, minute, and return value interval
3. I used arrays to process this week
4. Countdown mainly calculates the time difference, subtracts the number of seconds of the current time, and performs mathematical calculations.
5. Closures are used here to prevent multiple timers from conflicting
6. The code here is relatively easy to understand. Awesome people can transform it into a plug-in. I hope to share it.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.