Efficient Stopwatch

2019-04-28 23:38发布

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.

2条回答
再贱就再见
2楼-- · 2019-04-28 23:51

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.

查看更多
做个烂人
3楼-- · 2019-04-29 00:03

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

查看更多
登录 后发表回答