Small knowledge, big challenge! This paper is participating in theEssentials for programmers”Creative activities.

Hello! In my last article, I introduced the #uni.app to wechat and introduced the iconfont of Ali font. Today, I’m going to give you a simple and practical countdown function. Although the function is simple, but it is very strange that I can not write the code by hand every time, second-hand direct copy of the code in the past; There is no doubt that I am a tool man, a brick-moving programmer; Don’t copy me!

The text begins

Here’s what you want to achieve

Code implementation process

First, let’s go over the logic

Convert the time difference into days, hours, minutes and seconds to display. The main operation is to take the modulus of %. Get the number of milliseconds of the remaining end time (remaining milliseconds),

Divide by 1,000 to get the remaining seconds, divide by 60 to get the remaining minutes, divide by 60 to get the remaining hours. Divide by 24 to get the remaining days.

Remaining seconds time/1000 %60 gets seconds, remaining minutes time/(1000 * 60) %60 gets minutes,

Remaining hours time/(1000 * 60 * 60) %24

The background will pass a countdown time to you; So all I need to do is pass that parameter into the method that I’m going to write down

HTML section <body> <div id="countdown"></div> </body> <script> let timer let timeEvent = document.getElementById("countdown"); function countdown() { let nowTime = new Date(); // let endTime = new Date("2021/11/02"); TimeLog = endtime.getTime () -nowtime.getTime (); timeLog = endtime.getTime (); // Time difference // one step to get the timestamp is milliseconds; By the way, the 10-digit timestamp is in seconds, and the 13-digit timestamp is in milliseconds; let day = Math.floor(timeLog / (1000 * 60 * 60 * 24)); Math.floor((timeLog/(1000 * 60 * 60)) % 24); // let hour = math.floor ((timeLog/(1000 * 60 * 60)) % 24); Math.floor((timeLog/(1000 * 60)) % 60); // let min = math.floor ((timeLog/(1000 * 60)) % 60); // get min let SEC = math.floor ((timeLog / 1000) % 60); If (day==0 && hour==0 && min==0 && SEC ==0) {clearInterval(timer); countdown.style.display = "none"; } if (day == 0) { return (hour<10? '0'+hour:hour) + ":" + (min<10? '0'+min:min) + ":" + (sec<10? '0'+sec:sec); } else { return (day<10? '0'+ '0'+ '" + (hour<10? '0'+hour:hour) + ":" + (min<10? '0'+min:min) + ":" + (sec<10? '0'+sec:sec); Timer = setInterval(() => {timeEvent.innerhtml = countdown(); }, 1000); </script>Copy the code

Conclusion:

Well, that’s the end of the article, and I realize THAT I’m not sensitive to time stamps; Sometimes there is a mask; There are many ways to do this; Dig slowly;

I hope this article can help you; Then (like + comment + follow) if you have any questions, you can communicate with each other