Time with Javascript

How can I find out how much time elapses between two events using javascript? for example, to a millisecond?

+3
source share
6 answers

This is surprisingly hard to do.

var start = new Date();
// Do things here
var finish = new Date();
var difference = new Date();
difference.setTime(finish.getTime() - start.getTime());
alert( difference.getMilliseconds() );
+5
source

When performing arithmetic operations on objects, Datethey are implicitly converted to milliseconds (from 1970-01-01 00:00:00 UTC), so all you need to do is subtract Datecreated when the operation starts with Datecreated when the operation was completed.

var start = new Date();
doSomeHeavyWork();
var end = new Date();
var millisecondsElapsed = end - start;
+12
source

.

console.time("timer name")
console.timeEnd("timer name")

.

+10

, firebug ( firefox), . : javascript

+2

?

:

// event 1
document.getElementById('elId').onclick = function () {
  timer.start('myTimer1');
};

// event 2
document.getElementById('otherElement').onclick = function () {
  alert(timer.stop('myTimer1')); // alerts the time difference in ms
};

Implementation:

var timer = (function () {
  var startTimes = {}; // multiple start times will be stored here

  return {
    start: function (id) {
      id = id || 'default'; // set id = 'default' if no valid argument passed
      startTimes[id] = +new Date; // store the current time using the timer id
    },
    stop: function (id) {
      id = id || 'default';
      var diff = (+new Date - startTimes[id]); // get the difference
      delete startTimes[id]; // remove the stored start time
      return diff || undefined; // return the difference in milliseconds
    }
  };
}());
+2
source
var initialTime = (new Date).getTime(), i = 55000;

(function() {
    while ( i-- ) {
        setTimeout( function(){}, 20 );
    }
})()

var finalTime = ( new Date ).getTime(), diff = (new Date);

diff.setTime( finalTime - initialTime );

alert( diff.getMilliseconds() + 'ms' )
+1
source

Source: https://habr.com/ru/post/1718619/


All Articles