Find elapsed time in javascript












7















I'm new to JavaScript and I'm trying to write a code which calculates the time elapsed from the time a user logged 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 output is correct upto 00:59:59 but after that that O/P is:



00:59:59
01:59:59
01:59:00
01:59:01
.
.
.
.
01:59:59
01:00:00



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










share|improve this question




















  • 3





    Get the unixtimestamp and then calculate it from that. (Date.now())

    – NEO
    Jul 14 '15 at 12:02






  • 3





    if(minutes == 59 && seconds == 59) { hours; } doesn't do anything.

    – Magicprog.fr
    Jul 14 '15 at 12:02











  • I would suggest looking at a lib such as moment.js, it has a lot of utility functions for calculating durations, etc: momentjs.com

    – Ted Nyberg
    Jul 14 '15 at 12:07











  • by the way, its bad practice to work with global objects aka: "window.markDate"

    – Ori Price
    Jul 14 '15 at 12:14











  • There is no need for all that (or converting anything), because Date objects are directly comparable to each other! E.g., when I need to get double-click events (for simplicity, regardless of where the user clicked), I set a global variable LastClickTime=new Date(), then set an onclick function to get CurrentTime=new Date(), which checks if CurrentTime-LastClickTime<DoubleClickThreshold (to only consider "fast enough" clicks as double-clicks) and updates LastClickTime=CurrentTime (to be ready to capture next click). Don't forget that the timestamps are in milliseconds, though!

    – Cyberknight
    Oct 26 '18 at 18:29
















7















I'm new to JavaScript and I'm trying to write a code which calculates the time elapsed from the time a user logged 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 output is correct upto 00:59:59 but after that that O/P is:



00:59:59
01:59:59
01:59:00
01:59:01
.
.
.
.
01:59:59
01:00:00



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










share|improve this question




















  • 3





    Get the unixtimestamp and then calculate it from that. (Date.now())

    – NEO
    Jul 14 '15 at 12:02






  • 3





    if(minutes == 59 && seconds == 59) { hours; } doesn't do anything.

    – Magicprog.fr
    Jul 14 '15 at 12:02











  • I would suggest looking at a lib such as moment.js, it has a lot of utility functions for calculating durations, etc: momentjs.com

    – Ted Nyberg
    Jul 14 '15 at 12:07











  • by the way, its bad practice to work with global objects aka: "window.markDate"

    – Ori Price
    Jul 14 '15 at 12:14











  • There is no need for all that (or converting anything), because Date objects are directly comparable to each other! E.g., when I need to get double-click events (for simplicity, regardless of where the user clicked), I set a global variable LastClickTime=new Date(), then set an onclick function to get CurrentTime=new Date(), which checks if CurrentTime-LastClickTime<DoubleClickThreshold (to only consider "fast enough" clicks as double-clicks) and updates LastClickTime=CurrentTime (to be ready to capture next click). Don't forget that the timestamps are in milliseconds, though!

    – Cyberknight
    Oct 26 '18 at 18:29














7












7








7


1






I'm new to JavaScript and I'm trying to write a code which calculates the time elapsed from the time a user logged 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 output is correct upto 00:59:59 but after that that O/P is:



00:59:59
01:59:59
01:59:00
01:59:01
.
.
.
.
01:59:59
01:00:00



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










share|improve this question
















I'm new to JavaScript and I'm trying to write a code which calculates the time elapsed from the time a user logged 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 output is correct upto 00:59:59 but after that that O/P is:



00:59:59
01:59:59
01:59:00
01:59:01
.
.
.
.
01:59:59
01:00:00



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







javascript






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Jul 14 '15 at 12:07







Gaurav Mahawar

















asked Jul 14 '15 at 12:00









Gaurav MahawarGaurav Mahawar

1471212




1471212








  • 3





    Get the unixtimestamp and then calculate it from that. (Date.now())

    – NEO
    Jul 14 '15 at 12:02






  • 3





    if(minutes == 59 && seconds == 59) { hours; } doesn't do anything.

    – Magicprog.fr
    Jul 14 '15 at 12:02











  • I would suggest looking at a lib such as moment.js, it has a lot of utility functions for calculating durations, etc: momentjs.com

    – Ted Nyberg
    Jul 14 '15 at 12:07











  • by the way, its bad practice to work with global objects aka: "window.markDate"

    – Ori Price
    Jul 14 '15 at 12:14











  • There is no need for all that (or converting anything), because Date objects are directly comparable to each other! E.g., when I need to get double-click events (for simplicity, regardless of where the user clicked), I set a global variable LastClickTime=new Date(), then set an onclick function to get CurrentTime=new Date(), which checks if CurrentTime-LastClickTime<DoubleClickThreshold (to only consider "fast enough" clicks as double-clicks) and updates LastClickTime=CurrentTime (to be ready to capture next click). Don't forget that the timestamps are in milliseconds, though!

    – Cyberknight
    Oct 26 '18 at 18:29














  • 3





    Get the unixtimestamp and then calculate it from that. (Date.now())

    – NEO
    Jul 14 '15 at 12:02






  • 3





    if(minutes == 59 && seconds == 59) { hours; } doesn't do anything.

    – Magicprog.fr
    Jul 14 '15 at 12:02











  • I would suggest looking at a lib such as moment.js, it has a lot of utility functions for calculating durations, etc: momentjs.com

    – Ted Nyberg
    Jul 14 '15 at 12:07











  • by the way, its bad practice to work with global objects aka: "window.markDate"

    – Ori Price
    Jul 14 '15 at 12:14











  • There is no need for all that (or converting anything), because Date objects are directly comparable to each other! E.g., when I need to get double-click events (for simplicity, regardless of where the user clicked), I set a global variable LastClickTime=new Date(), then set an onclick function to get CurrentTime=new Date(), which checks if CurrentTime-LastClickTime<DoubleClickThreshold (to only consider "fast enough" clicks as double-clicks) and updates LastClickTime=CurrentTime (to be ready to capture next click). Don't forget that the timestamps are in milliseconds, though!

    – Cyberknight
    Oct 26 '18 at 18:29








3




3





Get the unixtimestamp and then calculate it from that. (Date.now())

– NEO
Jul 14 '15 at 12:02





Get the unixtimestamp and then calculate it from that. (Date.now())

– NEO
Jul 14 '15 at 12:02




3




3





if(minutes == 59 && seconds == 59) { hours; } doesn't do anything.

– Magicprog.fr
Jul 14 '15 at 12:02





if(minutes == 59 && seconds == 59) { hours; } doesn't do anything.

– Magicprog.fr
Jul 14 '15 at 12:02













I would suggest looking at a lib such as moment.js, it has a lot of utility functions for calculating durations, etc: momentjs.com

– Ted Nyberg
Jul 14 '15 at 12:07





I would suggest looking at a lib such as moment.js, it has a lot of utility functions for calculating durations, etc: momentjs.com

– Ted Nyberg
Jul 14 '15 at 12:07













by the way, its bad practice to work with global objects aka: "window.markDate"

– Ori Price
Jul 14 '15 at 12:14





by the way, its bad practice to work with global objects aka: "window.markDate"

– Ori Price
Jul 14 '15 at 12:14













There is no need for all that (or converting anything), because Date objects are directly comparable to each other! E.g., when I need to get double-click events (for simplicity, regardless of where the user clicked), I set a global variable LastClickTime=new Date(), then set an onclick function to get CurrentTime=new Date(), which checks if CurrentTime-LastClickTime<DoubleClickThreshold (to only consider "fast enough" clicks as double-clicks) and updates LastClickTime=CurrentTime (to be ready to capture next click). Don't forget that the timestamps are in milliseconds, though!

– Cyberknight
Oct 26 '18 at 18:29





There is no need for all that (or converting anything), because Date objects are directly comparable to each other! E.g., when I need to get double-click events (for simplicity, regardless of where the user clicked), I set a global variable LastClickTime=new Date(), then set an onclick function to get CurrentTime=new Date(), which checks if CurrentTime-LastClickTime<DoubleClickThreshold (to only consider "fast enough" clicks as double-clicks) and updates LastClickTime=CurrentTime (to be ready to capture next click). Don't forget that the timestamps are in milliseconds, though!

– Cyberknight
Oct 26 '18 at 18:29












7 Answers
7






active

oldest

votes


















3














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>








share|improve this answer

































    10














    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>








    share|improve this answer

































      2














      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





      share|improve this answer

































        0














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





        share|improve this answer
























        • This fixes one problem but not the other (between 1:59:59 and 2:00:00) because the hours variable is reset to zero every time.

          – JJJ
          Jul 14 '15 at 12:08











        • Bad habit to convert numbers to strings. You'll end up with problems in other languages, but Javascript won't really care.

          – MortenMoulder
          Jul 14 '15 at 12:11






        • 2





          Also, seconds == '00' doesn't do anything.

          – JJJ
          Jul 14 '15 at 12:15



















        0














        I would use the getTime() method, subtract the time and then convert the result into hh:mm:ss.mmm format.






        share|improve this answer































          0














          I know this is kindda old question but I'd like to apport my own solution in case anyone would like to have a JS encapsulated plugin for this. Ideally I would have: start, pause, resume, stop, reset methods. Giving the following code all of the mentioned can easily be 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>








          share|improve this answer































            0














            What I found useful is a 'port' of a C++ construct (albeit often in C++ I left show implicitly called by destructor):



            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 be used - for instance:



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





            share|improve this answer

























              Your Answer






              StackExchange.ifUsing("editor", function () {
              StackExchange.using("externalEditor", function () {
              StackExchange.using("snippets", function () {
              StackExchange.snippets.init();
              });
              });
              }, "code-snippets");

              StackExchange.ready(function() {
              var channelOptions = {
              tags: "".split(" "),
              id: "1"
              };
              initTagRenderer("".split(" "), "".split(" "), channelOptions);

              StackExchange.using("externalEditor", function() {
              // Have to fire editor after snippets, if snippets enabled
              if (StackExchange.settings.snippets.snippetsEnabled) {
              StackExchange.using("snippets", function() {
              createEditor();
              });
              }
              else {
              createEditor();
              }
              });

              function createEditor() {
              StackExchange.prepareEditor({
              heartbeatType: 'answer',
              autoActivateHeartbeat: false,
              convertImagesToLinks: true,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: 10,
              bindNavPrevention: true,
              postfix: "",
              imageUploader: {
              brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
              contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
              allowUrls: true
              },
              onDemand: true,
              discardSelector: ".discard-answer"
              ,immediatelyShowMarkdownHelp:true
              });


              }
              });














              draft saved

              draft discarded


















              StackExchange.ready(
              function () {
              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f31405996%2ffind-elapsed-time-in-javascript%23new-answer', 'question_page');
              }
              );

              Post as a guest















              Required, but never shown

























              7 Answers
              7






              active

              oldest

              votes








              7 Answers
              7






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              3














              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>








              share|improve this answer






























                3














                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>








                share|improve this answer




























                  3












                  3








                  3







                  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>








                  share|improve this answer















                  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>








                  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>





                  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>






                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Jun 1 '18 at 13:33









                  LWC

                  415423




                  415423










                  answered Jul 14 '15 at 12:14









                  CurtCurt

                  76.8k55233319




                  76.8k55233319

























                      10














                      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>








                      share|improve this answer






























                        10














                        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>








                        share|improve this answer




























                          10












                          10








                          10







                          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>








                          share|improve this answer















                          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>








                              var start = Date.now();

                          setInterval(function() {
                          document.getElementById('difference').innerHTML = Date.now() - start;

                          // the difference will be in ms
                          }, 1000);

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





                              var start = Date.now();

                          setInterval(function() {
                          document.getElementById('difference').innerHTML = Date.now() - start;

                          // the difference will be in ms
                          }, 1000);

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






                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Jun 1 '18 at 13:33









                          LWC

                          415423




                          415423










                          answered Jul 14 '15 at 12:08









                          Christian VargaChristian Varga

                          16.9k24266




                          16.9k24266























                              2














                              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





                              share|improve this answer






























                                2














                                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





                                share|improve this answer




























                                  2












                                  2








                                  2







                                  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





                                  share|improve this answer















                                  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





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





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






                                  share|improve this answer














                                  share|improve this answer



                                  share|improve this answer








                                  edited Nov 4 '18 at 6:09

























                                  answered Nov 4 '18 at 5:38









                                  agm1984agm1984

                                  3,88411936




                                  3,88411936























                                      0














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





                                      share|improve this answer
























                                      • This fixes one problem but not the other (between 1:59:59 and 2:00:00) because the hours variable is reset to zero every time.

                                        – JJJ
                                        Jul 14 '15 at 12:08











                                      • Bad habit to convert numbers to strings. You'll end up with problems in other languages, but Javascript won't really care.

                                        – MortenMoulder
                                        Jul 14 '15 at 12:11






                                      • 2





                                        Also, seconds == '00' doesn't do anything.

                                        – JJJ
                                        Jul 14 '15 at 12:15
















                                      0














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





                                      share|improve this answer
























                                      • This fixes one problem but not the other (between 1:59:59 and 2:00:00) because the hours variable is reset to zero every time.

                                        – JJJ
                                        Jul 14 '15 at 12:08











                                      • Bad habit to convert numbers to strings. You'll end up with problems in other languages, but Javascript won't really care.

                                        – MortenMoulder
                                        Jul 14 '15 at 12:11






                                      • 2





                                        Also, seconds == '00' doesn't do anything.

                                        – JJJ
                                        Jul 14 '15 at 12:15














                                      0












                                      0








                                      0







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





                                      share|improve this answer













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






                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      answered Jul 14 '15 at 12:05









                                      KramKram

                                      465411




                                      465411













                                      • This fixes one problem but not the other (between 1:59:59 and 2:00:00) because the hours variable is reset to zero every time.

                                        – JJJ
                                        Jul 14 '15 at 12:08











                                      • Bad habit to convert numbers to strings. You'll end up with problems in other languages, but Javascript won't really care.

                                        – MortenMoulder
                                        Jul 14 '15 at 12:11






                                      • 2





                                        Also, seconds == '00' doesn't do anything.

                                        – JJJ
                                        Jul 14 '15 at 12:15



















                                      • This fixes one problem but not the other (between 1:59:59 and 2:00:00) because the hours variable is reset to zero every time.

                                        – JJJ
                                        Jul 14 '15 at 12:08











                                      • Bad habit to convert numbers to strings. You'll end up with problems in other languages, but Javascript won't really care.

                                        – MortenMoulder
                                        Jul 14 '15 at 12:11






                                      • 2





                                        Also, seconds == '00' doesn't do anything.

                                        – JJJ
                                        Jul 14 '15 at 12:15

















                                      This fixes one problem but not the other (between 1:59:59 and 2:00:00) because the hours variable is reset to zero every time.

                                      – JJJ
                                      Jul 14 '15 at 12:08





                                      This fixes one problem but not the other (between 1:59:59 and 2:00:00) because the hours variable is reset to zero every time.

                                      – JJJ
                                      Jul 14 '15 at 12:08













                                      Bad habit to convert numbers to strings. You'll end up with problems in other languages, but Javascript won't really care.

                                      – MortenMoulder
                                      Jul 14 '15 at 12:11





                                      Bad habit to convert numbers to strings. You'll end up with problems in other languages, but Javascript won't really care.

                                      – MortenMoulder
                                      Jul 14 '15 at 12:11




                                      2




                                      2





                                      Also, seconds == '00' doesn't do anything.

                                      – JJJ
                                      Jul 14 '15 at 12:15





                                      Also, seconds == '00' doesn't do anything.

                                      – JJJ
                                      Jul 14 '15 at 12:15











                                      0














                                      I would use the getTime() method, subtract the time and then convert the result into hh:mm:ss.mmm format.






                                      share|improve this answer




























                                        0














                                        I would use the getTime() method, subtract the time and then convert the result into hh:mm:ss.mmm format.






                                        share|improve this answer


























                                          0












                                          0








                                          0







                                          I would use the getTime() method, subtract the time and then convert the result into hh:mm:ss.mmm format.






                                          share|improve this answer













                                          I would use the getTime() method, subtract the time and then convert the result into hh:mm:ss.mmm format.







                                          share|improve this answer












                                          share|improve this answer



                                          share|improve this answer










                                          answered Jul 14 '15 at 12:09









                                          cs04iz1cs04iz1

                                          9491025




                                          9491025























                                              0














                                              I know this is kindda old question but I'd like to apport my own solution in case anyone would like to have a JS encapsulated plugin for this. Ideally I would have: start, pause, resume, stop, reset methods. Giving the following code all of the mentioned can easily be 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>








                                              share|improve this answer




























                                                0














                                                I know this is kindda old question but I'd like to apport my own solution in case anyone would like to have a JS encapsulated plugin for this. Ideally I would have: start, pause, resume, stop, reset methods. Giving the following code all of the mentioned can easily be 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>








                                                share|improve this answer


























                                                  0












                                                  0








                                                  0







                                                  I know this is kindda old question but I'd like to apport my own solution in case anyone would like to have a JS encapsulated plugin for this. Ideally I would have: start, pause, resume, stop, reset methods. Giving the following code all of the mentioned can easily be 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>








                                                  share|improve this answer













                                                  I know this is kindda old question but I'd like to apport my own solution in case anyone would like to have a JS encapsulated plugin for this. Ideally I would have: start, pause, resume, stop, reset methods. Giving the following code all of the mentioned can easily be 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>








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





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






                                                  share|improve this answer












                                                  share|improve this answer



                                                  share|improve this answer










                                                  answered Jan 13 '17 at 11:56









                                                  dibilerdibiler

                                                  12




                                                  12























                                                      0














                                                      What I found useful is a 'port' of a C++ construct (albeit often in C++ I left show implicitly called by destructor):



                                                      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 be used - for instance:



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





                                                      share|improve this answer






























                                                        0














                                                        What I found useful is a 'port' of a C++ construct (albeit often in C++ I left show implicitly called by destructor):



                                                        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 be used - for instance:



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





                                                        share|improve this answer




























                                                          0












                                                          0








                                                          0







                                                          What I found useful is a 'port' of a C++ construct (albeit often in C++ I left show implicitly called by destructor):



                                                          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 be used - for instance:



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





                                                          share|improve this answer















                                                          What I found useful is a 'port' of a C++ construct (albeit often in C++ I left show implicitly called by destructor):



                                                          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 be used - for instance:



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






                                                          share|improve this answer














                                                          share|improve this answer



                                                          share|improve this answer








                                                          edited Feb 26 at 18:40

























                                                          answered Oct 4 '18 at 20:38









                                                          CapelliCCapelliC

                                                          51.7k43263




                                                          51.7k43263






























                                                              draft saved

                                                              draft discarded




















































                                                              Thanks for contributing an answer to Stack Overflow!


                                                              • Please be sure to answer the question. Provide details and share your research!

                                                              But avoid



                                                              • Asking for help, clarification, or responding to other answers.

                                                              • Making statements based on opinion; back them up with references or personal experience.


                                                              To learn more, see our tips on writing great answers.




                                                              draft saved


                                                              draft discarded














                                                              StackExchange.ready(
                                                              function () {
                                                              StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f31405996%2ffind-elapsed-time-in-javascript%23new-answer', 'question_page');
                                                              }
                                                              );

                                                              Post as a guest















                                                              Required, but never shown





















































                                                              Required, but never shown














                                                              Required, but never shown












                                                              Required, but never shown







                                                              Required, but never shown

































                                                              Required, but never shown














                                                              Required, but never shown












                                                              Required, but never shown







                                                              Required, but never shown







                                                              Popular posts from this blog

                                                              Costa Masnaga

                                                              Fotorealismo

                                                              Create new schema in PostgreSQL using DBeaver