开发者

Efficient Stopwatch

开发者 https://www.devze.com 2023-03-24 22:37 出处:网络
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:

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 开发者_如何学Gowould be very accurate, if anyone has any input about this that would be awesome as well.


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.


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

0

精彩评论

暂无评论...
验证码 换一张
取 消