Karue Benson Karue
Karue Benson Karue

Reputation: 1026

jQuery Count Down timer based on Remaining Days, Hours, Minutes and Seconds

I'm creating a system where I have to check the deadline based on the client's initialization. For example, if the client's initialization was today at time x and the deadline is tomorrow or future at time y, I would like to calculate the time remaining inform of a countdown timer. I have managed to get the time remaining and my problem is count down timer to show the remaining days, hours, minutes, and seconds.

The following HTML code indicates the remaining time to the deadline

<span style='color: green;'>
    <span class='e-m-days'>0</span> Days | 
    <span class='e-m-hours'>8</span> Hours | 
    <span class='e-m-minutes'>0</span> Minutes | 
    <span class='e-m-seconds'>1</span> Seconds
</span>

My jQuery code:

<script>
    $(function(){
        var days    = parseInt( $('.e-m-days').html() );
        var hours   = parseInt( $('.e-m-hours').html() );
        var minutes = parseInt( $('.e-m-minutes').html() );
        var seconds = parseInt( $('.e-m-seconds').html() );

        var minutesWrap = 0; 
        var hoursWrap = 0; 
        var daysWrap; 
        var hoursRem = hours;

        var timer = seconds; 
        var counter =seconds;

        function countOrdersRemainingTime(){
            var id = setTimeout(countOrdersRemainingTime, 1000); 

            if(timer < 0){
                minutesWrap ++; 

                timer = 59;

            }

            var minRem = minutes - minutesWrap; 

            if( minRem == -1 ){
                hoursWrap + 1;
                minRem = 59;
                var hoursRem = hours - 1;
            }

            if(days == 0 && hours == 0 && minutes == 0 && seconds == 0){
                clearTimeout(id);
            }






            $('.e-m-seconds').html(timer);
            $('.e-m-minutes').html(minRem);
            $('.e-m-hours').html(hoursRem);


            timer --; 
        }

        countOrdersRemainingTime();


    });
</script>

The key thing is to create a count down timer that counts until the deadline is reached, i.e until the number of days, hours, minutes, and seconds becomes zero. I have tried for hours with no success :(.

Upvotes: 3

Views: 8241

Answers (2)

Twisty
Twisty

Reputation: 30883

Consider the following example.

$(function() {
  function getCounterData(obj) {
    var days = parseInt($('.e-m-days', obj).text());
    var hours = parseInt($('.e-m-hours', obj).text());
    var minutes = parseInt($('.e-m-minutes', obj).text());
    var seconds = parseInt($('.e-m-seconds', obj).text());
    return seconds + (minutes * 60) + (hours * 3600) + (days * 3600 * 24);
  }

  function setCounterData(s, obj) {
    var days = Math.floor(s / (3600 * 24));
    var hours = Math.floor((s % (60 * 60 * 24)) / (3600));
    var minutes = Math.floor((s % (60 * 60)) / 60);
    var seconds = Math.floor(s % 60);

    console.log(days, hours, minutes, seconds);

    $('.e-m-days', obj).html(days);
    $('.e-m-hours', obj).html(hours);
    $('.e-m-minutes', obj).html(minutes);
    $('.e-m-seconds', obj).html(seconds);
  }

  var count = getCounterData($(".counter"));

  var timer = setInterval(function() {
    count--;
    if (count == 0) {
      clearInterval(timer);
      return;
    }
    setCounterData(count, $(".counter"));
  }, 1000);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="counter" style='color: green;'>
  <span class='e-m-days'>0</span> Days |
  <span class='e-m-hours'>8</span> Hours |
  <span class='e-m-minutes'>0</span> Minutes |
  <span class='e-m-seconds'>1</span> Seconds
</div>

Based on: https://www.w3schools.com/howto/howto_js_countdown.asp

Upvotes: 7

Joel Hager
Joel Hager

Reputation: 3442

I believe this is what you're looking for. I've added comments to show exactly what's happening. Please let me know if anything isn't clear. I just picked a random date as a target date, but you can change it to anything you want :)

$(document).ready(function() {
  const days = $(".e-m-days");
  const hours = $(".e-m-hours");
  const minutes = $(".e-m-minutes");
  const seconds = $(".e-m-seconds");
  
  const targetDate = new Date('May 17, 2020 03:24:00');
  
  function convertMillis(milliseconds, format) {
  var days, hours, minutes, seconds, total_hours, total_minutes, total_seconds;
  
  total_seconds = parseInt(Math.floor(milliseconds / 1000));
  total_minutes = parseInt(Math.floor(total_seconds / 60));
  total_hours = parseInt(Math.floor(total_minutes / 60));
  days = parseInt(Math.floor(total_hours / 24));

  seconds = parseInt(total_seconds % 60);
  minutes = parseInt(total_minutes % 60);
  hours = parseInt(total_hours % 24);
  
  switch(format) {
	case 's':
		return total_seconds;
	case 'm':
		return total_minutes;
	case 'h':
		return total_hours;
	case 'd':
		return days;
	default:
		return { d: days, h: hours, m: minutes, s: seconds };
    }
  };
  
  window.setInterval( function()
  {
    // Where we check if 'now' is greater than the target date
    var date = Date.now();
    if (date > targetDate)
    {
      // Where we break
      console.log("Expired");
      clearInterval();
    } else
    {
      // Where we set values
      var millis = targetDate - date;
      var millisObject = convertMillis(millis);

      // Display values in HTML
      days.text(millisObject.d);
      hours.text(millisObject.h);
      minutes.text(millisObject.m);
      seconds.text(millisObject.s);
    };
  }, 1000);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<span style='color: green;'>
    <span class='e-m-days'>0</span> Days | 
    <span class='e-m-hours'>0</span> Hours | 
    <span class='e-m-minutes'>0</span> Minutes | 
    <span class='e-m-seconds'>0</span> Seconds
</span>

Upvotes: 1

Related Questions