Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...