How to measure elapsed time with Javascript?

Hi, I am new to Javascript programming.

I created a simple game where the user needs to click on the boxes. The game ends when the user finishes clicking on 16 boxes.

I want to measure the elapsed time for the user to complete the game. How to do it with Javascript?

Edit: I should have been more clear. I have an algorithm in my head. I did my research. I looked at the different answers. But they were not useful because they showed their own code, which was hard for me to understand.

Start timer: when the user clicks on the first square

Timer: when the user clicks on the last field

Thanks.

+5
source share
2 answers

Click the "Start" button, then the "Finish" button. It will show you the number of seconds between two clicks.

Millisecond interval in timeDiff variable. Play with it to find seconds / minutes / hours / 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> 
+24
source
 var seconds = 0; setInterval(function () { seconds++; }, 1000); 

There you go, now you have a variable second counter. Since I don't know the context, you need to decide if you want to attach this variable to the object or make it global.

Set interval is just a function that takes a function as the first parameter and a few milliseconds to repeat the function as the second parameter.

You can also solve this problem by saving and comparing time.

0
source

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


All Articles