Find past tense in javascript

I am new to JavaScript and I am trying to write code that calculates the elapsed time since the user logs in to the current time.

Here is my code: -

function markPresent() {
    window.markDate = new Date();
    $(document).ready(function() {
        $("div.absent").toggleClass("present");
    });
    updateClock();
}

function updateClock() {    
    var markMinutes = markDate.getMinutes();
    var markSeconds = markDate.getSeconds();

    var currDate = new Date();
    var currMinutes = currDate.getMinutes();
    var currSeconds = currDate.getSeconds();
    var minutes = currMinutes - markMinutes;
    if(minutes < 0) { minutes += 60; }
    var seconds = currSeconds - markSeconds;
    if(seconds < 0) { seconds += 60; }

    if(minutes < 10) { minutes = "0" + minutes; }
    if(seconds < 10) { seconds = "0" + seconds; }

    var hours = 0;
    if(minutes == 59 && seconds == 59) { hours++; }
    if(hours < 10) { hours = "0" + hours; }

    var timeElapsed = hours+':'+minutes+':'+seconds;
    document.getElementById("timer").innerHTML = timeElapsed;
    setTimeout(function() {updateClock()}, 1000);
}

      

The result is correct until 00:59:59, but after that O / P:

00:59:59 1:59:59 1:59:00 1:59:01,,,, 1:59:59 1:00:00

How can I solve this and is there a more efficient way I can do this? Thank.

+8


source to share


8 answers


There's too much going on here.

An easier way would be to simply compare markDate

with the current date and reformat each time .

View demo: http://jsfiddle.net/7e4psrzu/



function markPresent() {
    window.markDate = new Date();
    $(document).ready(function() {
        $("div.absent").toggleClass("present");
    });
    updateClock();
}

function updateClock() {  
    var currDate = new Date();
    var diff = currDate - markDate;
    document.getElementById("timer").innerHTML = format(diff/1000);
    setTimeout(function() {updateClock()}, 1000);
}

function format(seconds)
{
var numhours = parseInt(Math.floor(((seconds % 31536000) % 86400) / 3600),10);
var numminutes = parseInt(Math.floor((((seconds % 31536000) % 86400) % 3600) / 60),10);
var numseconds = parseInt((((seconds % 31536000) % 86400) % 3600) % 60,10);
    return ((numhours<10) ? "0" + numhours : numhours)
    + ":" + ((numminutes<10) ? "0" + numminutes : numminutes)
    + ":" + ((numseconds<10) ? "0" + numseconds : numseconds);
}

markPresent();
      

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="timer"></div>
      

Run codeHide result


+3


source


No offense, but it's overwhelmed. Just store the start time the first time you run the script, and then subtract it from the current time every time the timer fires.

There are many tutorials on how to convert ms to a human readable timestamp, so there is no need to cover that here.



    var start = Date.now();
    
    setInterval(function() {
      document.getElementById('difference').innerHTML = Date.now() - start;
    
      // the difference will be in ms
    }, 1000);
      

<div id="difference"></div>
      

Run codeHide result


+11


source


Here is the solution I just made for my use case. I find it quite readable. The basic premise is to simply subtract the timestamp from the current timestamp and then divide it by the correct units:

const showElapsedTime = (timestamp) => {
    if (typeof timestamp !== 'number') return 'NaN'        

    const SECOND = 1000
    const MINUTE = 1000 * 60
    const HOUR = 1000 * 60 * 60
    const DAY = 1000 * 60 * 60 * 24
    const MONTH = 1000 * 60 * 60 * 24 * 30
    const YEAR = 1000 * 60 * 60 * 24 * 30 * 12
    
    // const elapsed = ((new Date()).valueOf() - timestamp)
    const elapsed = 1541309742360 - timestamp
    
    if (elapsed <= MINUTE) return '${Math.round(elapsed / SECOND)}s'
    if (elapsed <= HOUR) return '${Math.round(elapsed / MINUTE)}m'
    if (elapsed <= DAY) return '${Math.round(elapsed / HOUR)}h'
    if (elapsed <= MONTH) return '${Math.round(elapsed / DAY)}d'
    if (elapsed <= YEAR) return '${Math.round(elapsed / MONTH)}mo'
    return '${Math.round(elapsed / YEAR)}y'
}
      
const createdAt = 1541301301000

console.log(showElapsedTime(createdAt + 5000000))
console.log(showElapsedTime(createdAt))
console.log(showElapsedTime(createdAt - 500000000))
      

Run codeHide result


For example, if 3000 milliseconds have passed, then 3000 is greater than SECONDS

(1000) but less than MINUTES

(60000), so this function will divide 3000 by 1000 and return 3s

3 seconds.

If you want timestamps in seconds rather than milliseconds, change all instances from 1000

to 1

(which actually multiplies everything by 1000 to go from milliseconds to seconds (i.e. because 1000ms is 1s).

Here are the scaling units in a DRY form:

const SECOND = 1000
const MINUTE = SECOND * 60
const HOUR = MINUTE * 60
const DAY = HOUR * 24
const MONTH = DAY * 30
const YEAR = MONTH * 12

      

+2


source


var hours = 0;
if(minutes == 59 && seconds == 59) 
{ 
    hours = hours + 1; 
    minutes = '00'; 
    seconds == '00';
}

      

0


source


I would use the method getTime()

, subtract the time and then convert the result to hh: mm: ss.mmm .

0


source


I know this is an old question, but I would like to approximate my own solution in case anyone would like to have an encapsulated JS plugin to do this. Ideally I would like to: start, pause, resume, stop, reset methods. By providing the following code, all of the above can be easily added.

(function(w){
  
  var timeStart,
      timeEnd,
      started = false,
      startTimer = function (){
        this.timeStart = new Date();
        this.started = true;
      },
      getPartial = function (end) {
        if (!this.started)
          return 0;
        else {
          if (end) this.started = false;
          this.timeEnd = new Date();
          return (this.timeEnd - this.timeStart) / 1000;
        }
      },
      stopTime = function () {
        if (!this.started)
          return 0;
        else {
          return this.getPartial(true);
        }
      },
      restartTimer = function(){
        this.timeStart = new Date(); 
      };
  w.Timer = {
    start : startTimer,
    getPartial : getPartial,
    stopTime : stopTime,
    restart : restartTimer
  };
})(this);
      

<a href="#" onclick="Timer.start()">Start</a>
<a href="#" onclick="Timer.getPartial()">Partial</a>
<a href="#" onclick="Timer.stopTime()">Stop</a>
<a href="#" onclick="Timer.restart()">Restart</a>
      

Run codeHide result


0


source


What I found useful is the "port" of the C ++ construct (although often in C ++ I left the show

destructor implicitly invoked):

var trace = console.log
function elapsed(op) {
    this.op = op
    this.t0 = Date.now()
}
elapsed.prototype.show = function() {
    trace.apply(null, [this.op, 'msec', Date.now() - this.t0, ':'].concat(Array.from(arguments)))
}

      

to use - for example:

function debug_counters() {
    const e = new elapsed('debug_counters')
    const to_show = visibleProducts().length
    e.show('to_show', to_show)
}

      

0


source


You can just use performance.now ()

Example:

start = performance.now();

elapsedTime = performance.now() - start;

      

0


source







All Articles