在 Javascript 中,如何创建一个精确的毫秒计时器?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32307483/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In Javascript, how to create an accurate timer with milliseconds?
提问by Hanfei Sun
I saw a Javascript milliseconds timer demo HERE
我在这里看到了一个 Javascript 毫秒计时器演示
However, I found it very inaccurate because it uses setInterval
to increase one ms per time.
但是,我发现它非常不准确,因为它setInterval
每次增加一毫秒。
Does anyone have ideas about how to implement an accurate milliseconds timer in JS easily? Does it has to be done using Date
object?
有没有人知道如何在 JS 中轻松实现精确的毫秒计时器?是否必须使用Date
对象来完成?
回答by jfriend00
An accurate timer uses setTimeout()
or setInterval()
to regularly update a display, but NEVER to count the actual time. Because of Javascript's single threaded nature, a timer event may not occur exactly at the right time interval, but a call to Date.now()
will always give you the exact current system time.
准确的计时器使用setTimeout()
或setInterval()
定期更新显示,但永远不要计算实际时间。由于 Javascript 的单线程特性,计时器事件可能不会恰好在正确的时间间隔发生,但调用Date.now()
将始终为您提供确切的当前系统时间。
So, instead, you always use something like Date.now()
to get the current time and compare it to some previous time to calculate the actual elapsed time. This will be as accurate as the system clock on the computer is.
因此,相反,您总是使用类似的方法Date.now()
来获取当前时间并将其与之前的某个时间进行比较以计算实际经过的时间。这将与计算机上的系统时钟一样准确。
For example, here's a working timer display:
例如,这是一个工作计时器显示:
var startTime = Date.now();
var interval = setInterval(function() {
var elapsedTime = Date.now() - startTime;
document.getElementById("timer").innerHTML = (elapsedTime / 1000).toFixed(3);
}, 100);
<span id="timer"></span> s
回答by Quentin Roy
Yes. Using Date
will be much more accurate. setInterval
will not be triggered 'exactly' each milliseconds.
是的。使用Date
会更准确。setInterval
不会每毫秒“完全”触发。
var startTime, interval;
function start(){
startTime = Date.now();
interval = setInterval(function(){
updateDisplay(Date.now() - startTime);
});
}
function stop(){
clearInterval(interval);
}
function updateDisplay(currentTime){
// do your stuff
}
回答by Radu Toader
setInterval could be switchet with
setInterval 可以切换为
var x = 100; //ms time
var incrementFunction = function(){
//increment the watch/clock code
setTimeout(incrementFunction,x);
};
incrementFunction();
this will make a setTimeout function to be endless called, and set again. It seems that setTimeout, has bigger priority than setInterval, which could be delayed.
这将使 setTimeout 函数被无限调用,然后再次设置。似乎 setTimeout 比 setInterval 具有更大的优先级,后者可能会延迟。