Find elapsed time in javascript

前端 未结 9 535
死守一世寂寞
死守一世寂寞 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 03:57

    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)
    }
    
    0 讨论(0)
  • 2020-12-10 04:01

    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>

    0 讨论(0)
  • 2020-12-10 04:10
    var hours = 0;
    if(minutes == 59 && seconds == 59) 
    { 
        hours = hours + 1; 
        minutes = '00'; 
        seconds == '00';
    }
    
    0 讨论(0)
  • 2020-12-10 04:11

    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>

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

    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');
    });

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

    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
    
    0 讨论(0)
提交回复
热议问题