Search code examples
javascriptmomentjs

count exact 5 minutes from date


I faced up with problem to calculate exact 5 minutes from time. Here the scenario, from the server response I get dateTime in format YYYY-MM-DD HH:mm:ss after that I show up local timer on page which counts 5 minutes after that time. I do it with momentjs.

var output = document.getElementById('out');

var fromCount = '2017-02-22 00:23:50';
var toMins = moment(fromCount).add(5, 'minutes');
var toMinsCount = setInterval(function(){
  var now = moment();
  var diff = moment(toMins - now).format('mm:ss');
  if(diff==='00:00'){
    clearInterval(toMinsCount);
    // something more here
    output.innerText = 'times up change fromCount data time';
  }
  if(now>toMins){
    clearInterval(toMinsCount);
    output.innerText = 'change fromCount data time';
  } else {
    output.innerText = diff;
  }
},1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.min.js"></script>

<div id="out"></div>

Everything works nice BUT, sometimes when I add 5 minutes to date counter starts count from 5:13 or bit higher, it occurs when for example data from count = '2017-02-22 00:30:50' and now date = '2017-02-22 00:30:15'. So how can I avoid this problem and show local counter exact 5:00 minutes?

I need to count it from servers time because my counter depends on special event. And I should show for each user came to page same time from the moment server has catch. In local way each user will see it's own 5 min timer.


Solution

  • Ok, here the solution that fits my needs.

    function count5min(value) {
        $http.get('https://testfate.ru/time').then(function (resp) {
          // getting dateTime fromServer
    
          var realTime, toMins, diff;
    
          realTime = moment(resp.data.time).valueOf();
          diff = moment().valueOf() - realTime;
    
          var beforeStart = moment(value);
    
          toMins = moment(beforeStart).add(5, 'minutes');
    
          var toMinsCount = setInterval(function () {
            var now = moment().subtract(diff, 'milliseconds');
            var difference = moment(toMins - now).format('mm:ss');
            if (difference === '00:00') {
              clearInterval(toMinsCount);
            }
            if (now > toMins) {
              clearInterval(toMinsCount);
            } else {
              $(el).find('.short-timer').text(difference);
            }
          }, 1000);
    
        }, function (err) {
          console.error(err);
        });
      }
    

    So what I do is, getting time from server, found difference between local time and server time in ms, then in interval function subtract this difference from local time. Works like a charm for me. My friend suggest this idea to me.