[Solved] 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
Enquirer: Leonard

||

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>

Respondent: Leonard

Solution #2:

var seconds = 0;
setInterval(function () {
  seconds++;
}, 1000);

There you go, now you have a variable counting seconds elapsed. Since I don’t know the context, you’ll have to decide whether you want to attach that variable to an object or make it global.

Set interval is simply a function that takes a function as it’s first parameter and a number of milliseconds to repeat the function as it’s second parameter.

You could also solve this by saving and comparing times.

EDIT: This answer will provide very inconsistent results due to things such as the event loop and the way browsers may choose to pause or delay processing when a page is in a background tab. I strongly recommend using the accepted answer.

Respondent: Weedoze

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Leave a Reply

Your email address will not be published.