Find elapsed time in javascript

No offence, but this is massively over-enginered. Simply store the start time when the script first runs, then subtract that from the current time every time your timer fires.

There are plenty of tutorials on converting ms into a readable timestamp, so that doesn't need to be covered 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>

Here is a solution I just made for my use case. I find it is 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))

For example, if 3000 milliseconds elapsed, then 3000 is greater than SECONDS (1000) but less than MINUTES (60,000), so this function will divide 3000 by 1000 and return 3s for 3 seconds elapsed.

If you need timestamps in seconds instead of milliseconds, change all instances of 1000 to 1 (which effectively multiplies everything by 1000 to go from milliseconds to seconds (ie: because 1000ms per 1s).

Here are the scaling units in more 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

There's too much going on here.

An easier way would just be to compare markDate to the current date each time and reformat.

See 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>

We can also use console.time() and console.timeEnd() method for the same thing.

Syntax:

console.time(label);
console.timeEnd(label);

Label: The name to give the new timer. This will identify the timer; use the same name when calling console.timeEnd() to stop the timer and get the time output to the console.

let promise = new Promise((resolve, reject) => setTimeout(resolve, 400, 'resolved'));

// Start Timer
console.time('x');

promise.then((result) => {
  console.log(result);

  // End Timer
  console.timeEnd('x');
});

Tags:

Javascript