Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
976 views
in Technique[技术] by (71.8m points)

node.js setTimeout resolution is very low and unstable

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?

For example with sleep module:

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

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

From the setTimeout docs:

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

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

and notice the difference with this:

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

// 507ms

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...