Effective stopwatch

Hi, I am programming a stopwatch utility in javascript, and I have a question about efficiency and overhead. There are two ways that I have considered to make a stopwatch:

1. Save the start date and constantly measure the number of milliseconds that has been since that date.

2.Create an integer and increase its value at a given interval.

I want to know which one is most effective. In addition, I am not sure that option number 2 will be very accurate if anyone has any information about this, which would also be surprising.

+6
source share
2 answers

As others have said, go to # 1. If you want a clock that ticks every second (or a minute or something else), you must evaluate the time until the next β€œtick”, so setTimeout is called a few ms after the correct time , eg. to start immediately after the next whole second:

var d = new Date(); var interval = 1020 - d.getMilliseconds(); setTimeout(fn, interval); 

Thus, if execution for one call is delayed by a busy system, the next should be called approximately 20 ms after the next whole second.

+3
source

Option 2 will not be accurate, especially if you have a page with additional javascript for other purposes. Go with the first approach.

+3
source

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


All Articles