swarajd
swarajd

Reputation: 1007

Why is setTimeout firing earlier than it should?

I have a bit of node.js code as such:

var start = Date.now();

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

setTimeout(function() {
    console.log(Date.now() - start);
}, 2000);

Something strange happens when I run it on my machine. The times I get are something between 970 and 980, and something between 1970 and 1980. Why am I getting times that are earlier than the timeout times?

Upvotes: 0

Views: 788

Answers (2)

GitaarLAB
GitaarLAB

Reputation: 14645

From the node.js setTimeOut documentation:

It is important to note that your callback will probably not be called in exactly delay milliseconds - Node.js makes no guarantees about the exact timing of when the callback will fire, nor of the ordering things will fire in. The callback will be called as close as possible to the time specified.

However, there is a nanotimer to play with:
https://www.npmjs.org/package/nanotimer

Some related questions:

However, I do think +/- 30ms early is a bit much (compared to most browsers I've played with, they are usually no more than 10ms later (as long as the cpu isn't maxed out, that is)).

Upvotes: 1

Cristi Mihai
Cristi Mihai

Reputation: 2565

I believe you're experiencing these issues because of the Date precision. It can vary across platforms and browsers.

Here's a more detailed read on the accuracy of Date.

There are more high precision timers available on some platforms, but you will often have to do some mix and match (detect what's available and regress accordingly).

Upvotes: 2

Related Questions