Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Node.JS Accurate Timer

Node.JS Accurate Timer

Problem

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.

Problem courtesy of: sonnuforevis

Solution

Well 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.

Solution courtesy of: Farid Nouri Neshat

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Node.JS Accurate Timer

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×