javascript Node.JS 精准计时器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8263652/
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
Node.JS Accurate Timer
提问by sonnuforevis
How can I create a Node.JS accurate timer? It should look like a kitchen timer or a stopwatch.
我怎样才能创建一个 Node.JS 准确的计时器?它应该看起来像厨房计时器或秒表。
And I need accuracy, as much as possible. The application will promote some kind of "clicks war". I need to store every (concurrent) user's click, noting seconds and milliseconds (to tie the game).
我需要尽可能准确。该应用程序将促进某种“点击战”。我需要存储每个(并发)用户的点击,注意秒和毫秒(以配合游戏)。
How can I do it? Are there some code sample?
我该怎么做?有一些代码示例吗?
Thanks in advance.
提前致谢。
回答by Farid Nouri Neshat
Well You should have a look at microtimemodule, which gives you the time as accurate as microseconds. You can even measure CPU tick time with it!
好吧,您应该看看microtime模块,它为您提供精确到微秒的时间。你甚至可以用它来测量 CPU 滴答时间!
As of the code well you can do something like this (Storing the time in objects and then accessing them with the user
id, advantage would be no duplicate of the same user and faster access to one, if the user name is known):
从代码开始,您可以执行以下操作(将时间存储在对象中,然后使用user
id访问它们,如果知道用户名,则不会重复同一用户,并且可以更快地访问一个用户):
var microtime = require('microtime');
, clicks = {};
click(function(user){ // An event listener for received clicks
clicks[user] = microtime.now();
});
or (pushing all in an array, advantage would be that it can be sorted, and easily all of them be iterated)
或(将所有内容推送到数组中,优点是可以对其进行排序,并且可以轻松地迭代所有内容)
var microtime = require('microtime');
, clicks = [];
click(function(user){ // An event listener for received clicks
clicks.push({
user : user,
time : microtime.now()
});
});
As of node v0.8.0 you can use process.hrtime()
which will return an array both containing a relative seconds and nanoseconds to past.
从节点 v0.8.0 开始,您可以使用process.hrtime()
它将返回一个数组,其中包含相对秒数和过去的纳秒数。