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 开发者_如何学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.
精彩评论