Find elapsed time in javascript

前端 未结 9 536
死守一世寂寞
死守一世寂寞 2020-12-10 03:35

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

相关标签:
9条回答
  • 2020-12-10 04:18

    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>

    0 讨论(0)
  • 2020-12-10 04:22

    You can simply use performance.now()

    Example:

    start = performance.now();
    
    elapsedTime = performance.now() - start;
    
    0 讨论(0)
  • 2020-12-10 04:23

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

    0 讨论(0)
提交回复
热议问题