Find elapsed time in javascript

前端 未结 9 557
死守一世寂寞
死守一世寂寞 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条回答
  •  萌比男神i
    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);

提交回复
热议问题