How to measure time elapsed on Javascript? [duplicate]
I created a simple game that start and ends the timer when the user finishes clicking on 16 boxes.
I want to measure the elapsed time for the user to complete the game. How do I do it using Javascript?
I took a look at different answers like this, but I had hard time understanding others' code.
I would assume it to look like this.
Timer Start: When user clicks the first box
Timer End: When user clicks the last box
Solution 1:
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>