Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
546 views
in Technique[技术] by (71.8m points)

simple javascript code to calculate a countdown

I'm trying to edit following code to get the output I want.

function zoo_countdown_end_day() {
    if ($('.zoo-get-order-notice .end-of-day')[0]) {
        var offset = $('.end-of-day').data('timezone');
        var day = new Date();
        var utc = day.getTime() + (day.getTimezoneOffset() * 60000);
        let d = new Date(utc + (3600000*offset)),
        duration = 60 * (60 - d.getMinutes());
        let timer = duration, minutes;
        let hours = (23 - d.getHours());//kumudu edited this
        hours = hours < 10 ? '0' + hours : hours;
        let label_h = $('.zoo-get-order-notice .end-of-day').data('hours');
        let label_m = $('.zoo-get-order-notice .end-of-day').data('minutes');
        setInterval(function () {
            minutes = parseInt(timer / 60, 10);
            minutes = minutes < 10 ? "1" + minutes : minutes;
            $('.zoo-get-order-notice .end-of-day').text(hours + ' ' + label_h + ' ' + minutes + ' ' + label_m);
            if (--timer < 0) {
                timer = duration;
            }
        }, 1000);
    }
}
zoo_countdown_end_day();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="zoo-get-order-notice">
    <span class="end-of-day"
          data-timezone="+3"
          data-hours="1"
          data-minutes="3"></span>
</div>
question from:https://stackoverflow.com/questions/65918363/simple-javascript-code-to-calculate-a-countdown

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Ok, the long and short of this answer is that it uses 2 functions to help..

  1. countDown: this function takes in a functionwhileCountingDown, a numberforHowLong, then another functionwhenFinishedThen
    whileCountingDown being triggered EACH second with the parameter being the amount of time left in seconds
    forHowLong is the amount of seconds this countdown will last
    whenFinishedThen is a function that activates AFTER the countdown is over.. it can be anything(like making a new countdown as well)

  2. timeParse: this function takes in a numberseconds and then returns a string that looks like a more human version of time
    eg: timeParse(108010), 108010 is 30 hours and 10 seconds, and it would return "1 day, 6 hours, 0 minutes"

The combination of these functions are able to have a countdown system working very well.. I ALSO DO NOT KNOW WHERE YOU GET YOUR FUTURE TIME FROM,
but if you get it in a timestamp format(like 1611860671302, a value that I copied from new Date().getTime() as I was typing this),
the line where you see 30*3600, replace that line with ((dateStamp-new Date().getTime())/1000).toFixed(0)

//honestly I don't even see where it's counting down from so i just made a countdown function that works in seconds and scheduled 30 hours from now(from when you run code).. just the format would probably need changing(since i don't know what format you want)
function zoo_countdown_end_day() {
    var elem=$('.zoo-get-order-notice .end-of-day')[0]
    //like I said, I didn't even see where you're taking the future time from but I'll just give a future time the equivalent of +30 hours
    countDown(
      (t)=>elem.innerText=timeParse(t), //every second, remaining time shows in specified element
      30*3600, //seconds equivalent for 30 hours.. if you have a future dateStamp, before the countdown function, let dateStamp=this datestamp you would have, THEN change this line to.. ((dateStamp-new Date().getTime())/1000).toFixed(0)
      ()=>console.log("Timer Complete")
    )
}
zoo_countdown_end_day();



//...............................................................
//time parsing function(takes in seconds and returns a string of a formatted date[this is what can change to change the look])
function timeParse(seconds){
    var words=[
        (num)=>{if(num==1){return("second")}return("seconds")},//this would return a word for seconds
        (num)=>{if(num==1){return("minute")}return("minutes")},//this would return a word for minutes
        (num)=>{if(num==1){return("hour")}return("hours")},//this would return a word for hours
        (num)=>{if(num==1){return("day")}return("days")}//this would return a word for days
    ]
    var timeArr=[seconds]
    if(timeArr[0]>=60){//if seconds >= 1 minute
        timeArr.unshift(Math.floor(timeArr[0]/60))
        timeArr[1]=timeArr[1]%60
    
        if(timeArr[0]>=60){//if minutes >= 1 hour
            timeArr.unshift(Math.floor(timeArr[0]/60))
            timeArr[1]=timeArr[1]%60
      
            if(timeArr[0]>=24){//if hours >= 1 day
                timeArr.unshift(Math.floor(timeArr[0]/24))
                timeArr[1]=timeArr[1]%24
            }
        }
    }
    timeArr=timeArr.reverse()
    .map((a,i)=>`${a} ${words[i](a)}`)
    .reverse() //puts words to values and then reverses it back to correct order
  timeArr.splice(timeArr.length-1,1) //takes out seconds part from being returned leaving days, minutes and hours
  return(timeArr.join(', ')) //a mixture/combination of the forEach formatting(joining numbers with words), what is returned from words array and how they're joined contributes to the formatted look
}
//...............................................................
//countDown function(that works in seconds)
function countDown(whileCountingDown, forHowLong, whenFinishedThen){
    //basic run down is, whileCountingDown is a function, forHowLong is a number, whenFinishedThen is a function
    //in depth run down is:
    /*
    whileCountingDown(with parameter of how much time left in seconds) is activated every second until forHowLong seconds has passed, then whenFinishedThen is triggered
  */
  
    var i=setInterval(()=>{forHowLong--
        if(forHowLong<=0){//count finished, determine what happens next
            clearInterval(i); whenFinishedThen()
        }
        else{whileCountingDown(forHowLong)}//do this for each second of countdown
    },1000)
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="zoo-get-order-notice">
    <span class="end-of-day"
          data-timezone="+3"
          data-hours="1"
          data-minutes="3"></span>
</div>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...