Last Updated: February 25, 2016
·
4.305K
· alxlo

Precise timing in JavaScript with microtimer and nanotime

If the 1ms granularity of the regular timer object in JavaScript is to coarse for your project and you need to time events more precisely, e.g. for controlling some amazing hardware, have a look at the node packages microtime and nanotimer.

Microtime allows for measuring time in nanoseconds, e.g. for profiling or for checking if some hardware timeout requirements have been met. The real resolution depends of course on your hardware capabilities. Therefore microtime comes with a test to estimate your clock resolution.

Nanotimer gives you a handy timer object that can trigger your callback in the range of some microseconds, way better than the 1 millisecond resolution the normal timer provides. How precise this timer is, again, depends on your hardware and your system load. The timer allows for callbacks intervals in the nanosecond range, but personally I have some doubts about this. Anyway, you get a much more precise and faster timer that will do for a lot of tasks.