这个问题已经为浏览器解答了here https://stackoverflow.com/questions/7272395/monotonically-increasing-time-in-javascript, but window.performance.now()
显然在 Node.js 中不可用。
一些应用程序需要稳定的时钟,即随时间单调增加的时钟,不受系统时钟漂移的影响。例如,Java 有System.nanoTime() https://docs.oracle.com/javase/8/docs/api/java/lang/System.html#nanoTime--而 C++ 有std::chrono::steady_clock http://en.cppreference.com/w/cpp/chrono/steady_clock。 Node.js 中可以使用这样的时钟吗?
结果 Node.js 中的等价物是process.hrtime() https://nodejs.org/api/process.html#processhrtimebigint。根据文档:
[从 process.hrtime() 返回的时间]相对于过去的任意时间,与一天中的时间无关,因此不受时钟漂移的影响。
Example
假设我们想要每秒定期调用某个 REST 端点,处理其结果并将某些内容打印到日志文件中。考虑端点可能需要一段时间才能响应,例如从数百毫秒到超过一秒。我们不想同时发生两个请求,所以setInterval()
并不能完全满足我们的需求。
一个好的方法是第一次调用我们的函数,执行请求,处理它,然后调用setTimeout()
并重新安排另一次运行。但考虑到我们提出请求所花费的时间,我们希望每秒执行一次。这是使用我们的稳定时钟来做到这一点的一种方法(这将保证我们不会被系统时钟漂移所愚弄):
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();
我做了这个辅助函数time()
它转换返回的值process.hrtime.bigint()
毫秒分辨率的时间戳;对于这个应用程序来说,分辨率足够了。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)