node.js setTimeout分辨率非常低且不稳定 [英] node.js setTimeout resolution is very low and unstable

查看:148
本文介绍了node.js setTimeout分辨率非常低且不稳定的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对setTimeout的分辨率有疑问.当我将其设置为50毫秒时,范围从51甚至80毫秒不等.当我使用睡眠模块时,我能够获得大约50 µs的分辨率,那么setTimeout函数要至少获得1 ms的问题是什么?有什么办法可以解决/避免这种情况?睡眠的问题是,即使应调用回调函数,它也会延迟所有内容,它会等待...是否有另一种解决方案可以在50毫秒的延迟内拍摄某些事件?

I got a problem with resolution of setTimeout. When I set it to 50 ms, it varies from 51 to even 80 ms. When I use sleep module, I am able to get resolution like 50 µs, so what is the setTimeout function problem to get at least 1 ms? Is there any way to fix/avoid that? The problem with sleep is that it delays everything even when callback function should be shoot, it waits... Is there an alternative solution to shoot some events in delay of exactly 50 ms?

例如带有睡眠模块:

var start = new Date().getTime();
sleep.usleep(50);
console.log(new Date().getTime() - start);`

结果是:0.微时间表示为51到57 µs.那到底是什么?

Result is: 0. And microtime says it is 51 to 57 µs. So what the hell?

推荐答案

来自 setTimeout文档:

重要的是要注意,您的回调可能不会在确切的延迟毫秒内被调用

It is important to note that your callback will probably not be called in exactly delay milliseconds

延迟的精度取决于代码块的数量,这意味着如果在代码具有的单个线程上执行大量操作,则setTimeout可能会延迟很多时间来触发.相反,这几乎是正确的.

The precision of the delay is determined by how little your code blocks, meaning that if you do a lot of operations on the single thread that your code has, the setTimeout might be triggered with a lot of delay. On the opposite, it will be almost exact.

您可以亲自看到差异,执行此操作

You could see the difference for yourself, execute this

var start = Date.now();
setTimeout(function() { console.log(Date.now() - start); }, 500);
for(var i=0; i<999999999; ++i){}

// 1237ms

并注意与此不同:

var start = Date.now();
setTimeout(function() { console.log(Date.now() - start); }, 500);

// 507ms

这篇关于node.js setTimeout分辨率非常低且不稳定的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆