Skip to content
Advertisement

Monotonically increasing time in Node.js

This question has already been answered for the browser here, but window.performance.now() is obviously not available in Node.js.

Some applications need a steady clock, i.e., a clock that monotonically increases through time, not subject to system clock drifts. For instance, Java has System.nanoTime() and C++ has std::chrono::steady_clock. Is such clock available in Node.js?

Advertisement

Answer

Turns out the equivalent in Node.js is process.hrtime(). As per the documentation:

[The time returned from process.hrtime() is] relative to an arbitrary time in the past, and not related to the time of day and therefore not subject to clock drift.


Example

Let’s say we want to periodically call some REST endpoint once a second, process its outcome and print something to a log file. Consider the endpoint may take a while to respond, e.g., from hundreds of milliseconds to more than one second. We don’t want to have two concurrent requests going on, so setInterval() does not exactly meet our needs.

One good approach is to call our function one first time, do the request, process it and then call setTimeout() and reschedule for another run. But we want to do that once a second, taking into account the time we spent making the request. Here’s one way to do it using our steady clock (which will guarantee we won’t be fooled by system clock drifts):

function time() {
    const nanos = process.hrtime.bigint();
    return Number(nanos / 1_000_000n);
}

async function run() {
    const startTime = time();

    const response = await doRequest();
    await processResponse(response);

    const endTime = time();
    // wait just the right amount of time so we run once second; 
    // if we took more than one second, run again immediately
    const nextRunInMillis = Math.max(0, 1000 - (endTime - startTime));
    setTimeout(run, nextRunInMillis);
}

run();

I made this helper function time() which converts the value returned by process.hrtime.bigint() to a timestamp with milliseconds resolution; just enough resolution for this application.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement