Nodejs 中的精确计时器
我正在构建一个实时国际象棋应用程序,并尝试为其添加一个计时器。然而,我正在努力寻找一种使计时器准确的方法。我运行了一些测试,setInterval
和 setTimeout
非常不准确,十分钟的超时时间相差了三分钟多。我还尝试以 100 毫秒的间隔使用 setInterval,但当选项卡未处于活动状态时,即使这样也会关闭一分钟多。这只是使用 javascript window.setInterval
;使用nodejs,它不会超过10毫秒,但如果服务器繁忙,我担心它会超过10毫秒。我希望找到一种方法让游戏在实时时间的至少十分之一秒内结束。
有什么建议吗?谢谢!
I'm building a live chess app, and I'm trying to add a timer to it. However, I am struggling to find a way to make the timer accurate. I have run some tests, and setInterval
and setTimeout
are extremely inaccurate, with a ten minute timeout being off by over three minutes. I also tried using setInterval with in interval of 100ms, but even that was off by over minute, when the tab was not active. That was just with the javascript window.setInterval
; with nodejs, it hasn't been more than 10ms off, but I'm afraid it will if the server gets busy. I'm hoping to find a way to have the game end within at least a tenth of a second of the real time.
Any suggestions? Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
理想的方法是使用绝对时钟时间来获取经过的时间,并使用计时器来进行检查。
像下面的代码一样。
由于性能原因,浏览器不会按要求运行 setInterval。
https://usefulangle.com/post/280/settimeout-setinterval- on-inactive-tab
如果您需要以所需的时间间隔运行计时器,那么它可以在工作线程中运行。
这里有一些信息。
我该如何制作当 Chrome 中的选项卡处于非活动状态时,setInterval 也可以工作吗?
但我的猜测是,增加粒度对于非活动选项卡来说是可以的。
an ideal approach would be to use absolute clock time to get time elapsed and timer to have that check.
Something like code below.
The browser will not run setInterval as required due to performance reason.
https://usefulangle.com/post/280/settimeout-setinterval-on-inactive-tab
If you need to run timer with required interval then it can be run in worker thread.
some info here.
How can I make setInterval also work when a tab is inactive in Chrome?
But my guess is increased granularity is fine for non active tab.