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
This question is related to
javascript
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.
Source: Stackoverflow.com