高效的秒表 [英] Efficient Stopwatch

查看:104
本文介绍了高效的秒表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好我正在使用javascript编写秒表实用程序,我对效率和开销有疑问。我有两种方法考虑制作秒表:

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.存储一个开始日期并不断测量自该日期以来的毫秒数。

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

2.创建一个整数并以设定的间隔递增其值。

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

我想知道哪个是最有效的。此外,我不确定选项#2是否会非常准确,如果有人对此有任何意见也会很棒。

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。如果你想要一个每秒(或分钟或其他)滴答的时钟,你应该估计到下一个滴答的时间,以便在正确的时间之后几毫秒调用 setTimeout ,例如在下一整秒后运行:

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);

这样一来,如果一个电话的执行因系统繁忙而延迟,那么下一个应该仍然是在下一整秒后大约20ms调用。

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.

这篇关于高效的秒表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆