1

I am working on a page that allows an employee to keep track of how long it takes them to complete a task. There are two buttons, start and stop that save the actually timestamps in the database.

However I want to give some type of visual counter as well, even thought the data from the counter it self will have no say in the starting and stopping of the timer; its all based on the timestamps.

I found a countdown plugin that I reversed and made it count up to a date way in the future. As soon as they click "Start", the timer begins to count up to it.

I am trying to build in a way to start the timer from a certain time if the user was to leave and come back.

For example if the task has a timestamp of September 1, 2015 at 12:00 then the timer would start at 4 days x hours x mins.

I added a setting onto the plugin called resume and startTime which triggers the resumeTimer function.

Any thoughts on how I can do this?

Here is a snippet:

var globalContainer;

(function($) {

  $.fn.upCount = function(options, callback) {
    var settings = $.extend({
      startTime: null,
      offset: null,
      reset: null,
      resume: null
    }, options);

    // Save container
    var container = this;
    globalContainer = container.parent().html();

    /**
     * Change client's local date to match offset timezone
     * @return {Object} Fixed Date object.
     */
    var currentDate = function() {
      // get client's current date
      var date = new Date();

      // turn date to utc
      var utc = date.getTime() + (date.getTimezoneOffset() * 60000);

      // set new Date object
      var new_date = new Date(utc + (3600000 * settings.offset))

      return new_date;
    };

    // Are we resetting our counter?
    if (settings.reset) {
      reset();
    }

    // Do we need to start our counter at a certain time if we left and came back?
    if (settings.startTime) {
      resumeTimer(new Date(settings.startTime));
    }

    // Define some global vars
    var original_date = currentDate();
    //console.log(currentDate())
    var target_date = new Date('12/31/2020 12:00:00'); // Count up to this date

    // Reset the counter by destroying the element it was bound to
    function reset() {
      var timerContainer = $('[name=timerContainer]');
      timerContainer.empty().append(globalContainer).find('.time').empty().append('00');
    }

    // Given a start time, lets set the timer
    function resumeTimer(startTime) {
      alert('Resume Timer Needs to Start From StartTime  ' + startTime)
      // This takes the difference between the startTime provided and the current date.
      // If the difference was 4 days and 25 mins, thats where the timer would start from continuing to count up
    }

    // Start the counter
    function countUp() {

      // Set our current date
      var current_date = currentDate();

      // difference of dates
      var difference = current_date - original_date;

      if (current_date >= target_date) {
        // stop timer
        clearInterval(interval);
        if (callback && typeof callback === 'function') callback();
        return;
      }

      // basic math variables
      var _second = 1000,
        _minute = _second * 60,
        _hour = _minute * 60,
        _day = _hour * 24;

      // calculate dates
      var days = Math.floor(difference / _day),
        hours = Math.floor((difference % _day) / _hour),
        minutes = Math.floor((difference % _hour) / _minute),
        seconds = Math.floor((difference % _minute) / _second);

      // fix dates so that it will show two digets
      days = (String(days).length >= 2) ? days : '0' + days;
      hours = (String(hours).length >= 2) ? hours : '0' + hours;
      minutes = (String(minutes).length >= 2) ? minutes : '0' + minutes;
      seconds = (String(seconds).length >= 2) ? seconds : '0' + seconds;

      // based on the date change the refrence wording
      var ref_days = (days === 1) ? 'day' : 'days',
        ref_hours = (hours === 1) ? 'hour' : 'hours',
        ref_minutes = (minutes === 1) ? 'minute' : 'minutes',
        ref_seconds = (seconds === 1) ? 'second' : 'seconds';

      // set to DOM
      container.find('.days').text(days);
      container.find('.hours').text(hours);
      container.find('.minutes').text(minutes);
      container.find('.seconds').text(seconds);

      container.find('.days_ref').text(ref_days);
      container.find('.hours_ref').text(ref_hours);
      container.find('.minutes_ref').text(ref_minutes);
      container.find('.seconds_ref').text(ref_seconds);
    };

    // start
    interval = setInterval(countUp, 1000);
  };

})(jQuery);


// Resume our timer from a specific time
$('.countdown').upCount({
  startTime: '09/01/2015 12:00:00',
  resume: true
});
ul.countdown {
  list-style: none;
  margin: 15px 15px;
  padding: 0;
  display: block;
  text-align: center;
}

ul.countdown li {
  display: inline-block;
}

ul.countdown li span {
  font-size: 80px;
  font-weight: 300;
  line-height: 80px;
}

ul.countdown li.seperator {
  font-size: 80px;
  line-height: 70px;
  vertical-align: top;
}

ul.countdown li p {
  color: #a7abb1;
  font-size: 14px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<div class="container">
  <div class="jumbotron" name="timerContainer">
    <center>
      <span name="timerContainer">
         <ul class="countdown">
            <li>
               <span class="days time">00</span>
      <p class="days_ref">days</p>
      </li>
      <li class="seperator">.</li>
      <li>
        <span class="hours time">00</span>
        <p class="hours_ref">hours</p>
      </li>
      <li class="seperator">:</li>
      <li>
        <span class="minutes time">00</span>
        <p class="minutes_ref">minutes</p>
      </li>
      <li class="seperator">:</li>
      <li>
        <span class="seconds time">00</span>
        <p class="seconds_ref">seconds</p>
      </li>
      </ul>
      </span>
    </center>
  </div>
</div>

enter image description here

Goran Stoyanov
  • 2,311
  • 1
  • 21
  • 31
SBB
  • 8,560
  • 30
  • 108
  • 223

2 Answers2

0

Looks like inside the countUp function, instead of subtracting original_date you just need to subtract new Date(settings.startTime). That way you're calculating the difference in time from the passed in start time instead of the time from when the page is opened.

Working snippet with a change:

var globalContainer;

(function($) {
  $.fn.upCount = function(options, callback) {
    var settings = $.extend({
      startTime: null,
      offset: null,
      reset: null,
      resume: null
    }, options);

    // Save container
    var container = this;
    globalContainer = container.parent().html();

    /**
     * Change client's local date to match offset timezone
     * @return {Object} Fixed Date object.
     */
    var currentDate = function() {
      // get client's current date
      var date = new Date();

      // turn date to utc
      var utc = date.getTime() + (date.getTimezoneOffset() * 60000);

      // set new Date object
      var new_date = new Date(utc + (3600000 * settings.offset))

      return new_date;
    };

    // Are we resetting our counter?
    if (settings.reset) {
      reset();
    }

    // Do we need to start our counter at a certain time if we left and came back?
    if (settings.startTime) {
      resumeTimer(new Date(settings.startTime));
    }

    // Define some global vars
    var original_date = currentDate();
    //console.log(currentDate())
    var target_date = new Date('12/31/2020 12:00:00'); // Count up to this date

    // Reset the counter by destroying the element it was bound to
    function reset() {
      var timerContainer = $('[name=timerContainer]');
      timerContainer.empty().append(globalContainer).find('.time').empty().append('00');
    }

    // Given a start time, lets set the timer
    function resumeTimer(startTime) {
      alert('Resume Timer Needs to Start From StartTime  ' + startTime)
      // This takes the difference between the startTime provided and the current date.
      // If the difference was 4 days and 25 mins, thats where the timer would start from continuing to count up
    }

    // Start the counter
    function countUp() {

      // Set our current date
      var current_date = currentDate();

      // difference of dates
      var difference = current_date - new Date(settings.startTime);

      if (current_date >= target_date) {
        // stop timer
        clearInterval(interval);
        if (callback && typeof callback === 'function') callback();
        return;
      }

      // basic math variables
      var _second = 1000,
        _minute = _second * 60,
        _hour = _minute * 60,
        _day = _hour * 24;

      // calculate dates
      var days = Math.floor(difference / _day),
        hours = Math.floor((difference % _day) / _hour),
        minutes = Math.floor((difference % _hour) / _minute),
        seconds = Math.floor((difference % _minute) / _second);

      // fix dates so that it will show two digets
      days = (String(days).length >= 2) ? days : '0' + days;
      hours = (String(hours).length >= 2) ? hours : '0' + hours;
      minutes = (String(minutes).length >= 2) ? minutes : '0' + minutes;
      seconds = (String(seconds).length >= 2) ? seconds : '0' + seconds;

      // based on the date change the refrence wording
      var ref_days = (days === 1) ? 'day' : 'days',
        ref_hours = (hours === 1) ? 'hour' : 'hours',
        ref_minutes = (minutes === 1) ? 'minute' : 'minutes',
        ref_seconds = (seconds === 1) ? 'second' : 'seconds';

      // set to DOM
      container.find('.days').text(days);
      container.find('.hours').text(hours);
      container.find('.minutes').text(minutes);
      container.find('.seconds').text(seconds);

      container.find('.days_ref').text(ref_days);
      container.find('.hours_ref').text(ref_hours);
      container.find('.minutes_ref').text(ref_minutes);
      container.find('.seconds_ref').text(ref_seconds);
    };

    // start
    interval = setInterval(countUp, 1000);
  };

})(jQuery);


// Resume our timer from a specific time
$('.countdown').upCount({
  startTime: '09/01/2015 12:00:00',
  resume: true
});
ul.countdown {
  list-style: none;
  margin: 15px 15px;
  padding: 0;
  display: block;
  text-align: center;
}

ul.countdown li {
  display: inline-block;
}

ul.countdown li span {
  font-size: 80px;
  font-weight: 300;
  line-height: 80px;
}

ul.countdown li.seperator {
  font-size: 80px;
  line-height: 70px;
  vertical-align: top;
}

ul.countdown li p {
  color: #a7abb1;
  font-size: 14px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<div class="container">
  <div class="jumbotron" name="timerContainer">
    <center>
      <span name="timerContainer">
         <ul class="countdown">
            <li>
               <span class="days time">00</span>
      <p class="days_ref">days</p>
      </li>
      <li class="seperator">.</li>
      <li>
        <span class="hours time">00</span>
        <p class="hours_ref">hours</p>
      </li>
      <li class="seperator">:</li>
      <li>
        <span class="minutes time">00</span>
        <p class="minutes_ref">minutes</p>
      </li>
      <li class="seperator">:</li>
      <li>
        <span class="seconds time">00</span>
        <p class="seconds_ref">seconds</p>
      </li>
      </ul>
      </span>
    </center>
  </div>
</div>
Goran Stoyanov
  • 2,311
  • 1
  • 21
  • 31
KhalilRavanna
  • 5,768
  • 3
  • 28
  • 24
0

Use this code. Seconds are approximate .

var isPaused = false;
var StartDate = new Date('2015', '08', '01', 00, 0, 0) // second parameter is  month and it is from  from 0-1
$('#spanStartDate').text(StartDate);
var Sec = 0,
    Min = 0,
    Hour = 0,
    Days = 0;
var CurrentDate = new Date()
var Diff = CurrentDate - StartDate;
Diff = Diff / 1000
if (Diff > 0) {
    Days = Math.ceil(Diff / (60 * 60 * 24));
    Hour = Math.floor(Diff % (24) / 60);
    Min = Math.floor(Diff % (24 * 60) / 60);
    Sec = Math.floor(Diff % (24 * 60 * 60) / 60);
    console.log(Sec)
}
var counter = setInterval(function () {
    if(isPaused)
        return;
    if (Sec == 0)++Sec;
    else Sec++
    if (Sec == 59) {
        ++Min;
        Sec = 0;
    }
    if (Min == 59) {
        ++Hour;
        Min = 0;
    }
    if (Hour == 24) {
        ++Days;
        Hour = 0;
    }


    $('#timer').text(pad(Days) + " : " + pad(Hour) + " : " + pad(Min) + " : " + pad(Sec));

}, 1000);

function pad(number) {
    if (number <= 9) {
        number = ("0" + number).slice(-4);
    }
    return number;
}


//with jquery
$('.pause').on('click', function(e) {
    e.preventDefault();
    isPaused = true;
});

$('.play').on('click', function(e) {
    e.preventDefault();
    isPaused = false;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="#" class="play">Play</a>
<a href="#" class="pause">Pause</a>

<br/><br/>

Start Time - &nbsp;&nbsp;&nbsp;&nbsp;<span id="spanStartDate"></span>

<br/>
<br/>Timer (DD:HH:MM:SS) - <span id="timer"></span>

<br/>
<br/>

Play and Pause Code from here

Community
  • 1
  • 1
J Santosh
  • 3,808
  • 2
  • 22
  • 43