This article shares a javascript implementation of a countdown for a limited-time sale, with a countdown accurate to milliseconds for your reference. The specific content is as follows
1. Renderings
The picture below is the effect of the limited time grab on Juhuasuan
2. Knowledge needed to achieve the limited time grab effect: Javascript Date() object
Date() returns the current date and event
getYear() returns the year. It is best to get the year
getFullYear() method to operate (full format as 2016)
getMonth() returns the month value (starting from 0, +1)
getDay() returns the day of the week (0-6)
getHours() returns the number of hours (0-23)
getMinutes() returns the number of minutes (0-59)
getSeconds() returns the number of seconds
getTime() returns the number of milliseconds
Of course, we may not necessarily use all the above calling methods. It also depends on your own needs. Without further ado, let’s go directly to the code:
1. HTML page code:
tag with class left-time.
2. JS script:
$(function(){ function leftTime(){ var endTime = new Date("2016/5/20,12:00:00");//结束时间 var curTime = new Date();//当前时间 var leftTime = parseInt((endTime.getTime() - curTime.getTime())/1000);//获得时间差 //小时、分、秒需要取模运算 var d = parseInt(leftTime/(60*60*24)); var h = parseInt(leftTime/(60*60)%24); var m = parseInt(leftTime/60%60); var s = parseInt(leftTime%60); var ms = parseInt(((endTime.getTime() - curTime.getTime())/100)%10); var txt = "剩余:"+d+"天"+h+"小时"+m+"分钟"+s+"."+ms+"秒"; $(".left-time").text(txt); if(leftTime<=0){ $(".left-time").text("团购结束");} }; leftTime(); var set = setInterval(leftTime,100); });
The above js implements a simple example of limited time grabbing. The parseInt() method is rounding, and getTime() converts the time into milliseconds. In addition to the parseInt() method, you can also use Math.floor () is replaced by rounding down.
Finally, remember not to forget to give an if() to determine what needs to be displayed when the time is over, otherwise unnecessary bugs will appear!