admin管理员组文章数量:1208155
How can I create a Node.JS accurate timer? It should look like a kitchen timer or a stopwatch.
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.
How can I create a Node.JS accurate timer? It should look like a kitchen timer or a stopwatch.
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.
Share Improve this question edited Feb 5, 2014 at 4:26 Farid Nouri Neshat 30.4k6 gold badges77 silver badges125 bronze badges asked Nov 25, 2011 at 0:05 sonnuforevissonnuforevis 1,3117 gold badges22 silver badges38 bronze badges 1- 1 Worth a note for the new native API for it nodejs.org/api/process.html#process_process_hrtime - see the link for possible usages – Fabiano Soriani Commented Mar 2, 2015 at 21:07
1 Answer
Reset to default 24Well You should have a look at microtime module, which gives you the time as accurate as microseconds. You can even measure CPU tick time with it!
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):
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.
本文标签: javascriptNodeJS Accurate TimerStack Overflow
版权声明:本文标题:javascript - Node.JS Accurate Timer - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738712083a2108255.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论