Efficient Stopwatch

爷,独闯天下 提交于 2019-12-07 03:19:32

问题


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.


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/6935920/efficient-stopwatch

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!