How to measure time elapsed on Javascript?
The Date
documentation states that :
The JavaScript date is based on a time value that is milliseconds since midnight January 1, 1970, UTC
Click on start button then on end button. It will show you the number of seconds between the 2 clicks.
The milliseconds diff is in variable timeDiff
. Play with it to find seconds/minutes/hours/ or what you need
var startTime, endTime;
function start() {
startTime = new Date();
};
function end() {
endTime = new Date();
var timeDiff = endTime - startTime; //in ms
// strip the ms
timeDiff /= 1000;
// get seconds
var seconds = Math.round(timeDiff);
console.log(seconds + " seconds");
}
<button onclick="start()">Start</button>
<button onclick="end()">End</button>
OR another way of doing it for modern browser
Using performance.now()
which returns a value representing the time elapsed since the time origin. This value is a double with microseconds in the fractional.
The time origin is a standard time which is considered to be the beginning of the current document's lifetime.
var startTime, endTime;
function start() {
startTime = performance.now();
};
function end() {
endTime = performance.now();
var timeDiff = endTime - startTime; //in ms
// strip the ms
timeDiff /= 1000;
// get seconds
var seconds = Math.round(timeDiff);
console.log(seconds + " seconds");
}
<button onclick="start()">Start</button>
<button onclick="end()">End</button>