Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Efficient Stopwatch

Hi I'm programming a stopwatch utility in javascript and I have a question about efficiency and overhead. There are two ways I have considered making the stopwatch:

1.Store a start Date and constantly measure the number of milliseconds it has been since that date.

2.Create an integer and increment its value at a set interval.

I want to know which is most efficient. Also, I'm not sure if option #2 would be very accurate, if anyone has any input about this that would be awesome as well.

like image 951
Drew Galbraith Avatar asked Aug 04 '11 03:08

Drew Galbraith


1 Answers

As others have said, go with #1. If you want a clock that ticks each second (or minute or whatever) you should estimate the time to the next "tick" so that setTimeout is called a few ms after the right time, e.g. to run just after the next whole second:

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

That way if execution for one call is delayed by the system being busy, the next one should still be called about 20ms after the next whole second.

like image 175
RobG Avatar answered Oct 10 '22 05:10

RobG