Reputation: 142
Question is straight forward.
e.g. i need to execute some code after at least 50 ms (not 49.8 ms).
// min-timeout.spec.js
const util = require('util');
const {performance} = require('perf_hooks');
const wait = util.promisify(setTimeout);
it.only('setTimeout() minimum delay', async() => {
for (let i = 0; i < 10; i++) {
const start = performance.now();
await wait(50);
const time = performance.now() - start;
console.log('time:', time);
}
});
Output:
time: 51.01539999991655
time: 50.70590000227094
time: 50.79270000010729
time: 50.22399900108576
time: 49.343199998140335
time: 50.81929999962449
time: 49.999699000269175
time: 49.83229999989271
time: 50.78200000151992
time: 50.010999999940395
Why sometimes execution time is less than 50 ms? Is it system dependent? How to ensure minimum delay at setTimeout() in Node.js?
System info:
Microsoft Windows [Version 10.0.17134.285]
node v8.11.2
Upvotes: 2
Views: 373
Reputation: 222865
The problem is specific to how timers are scheduled in Node.js within event loop. It's possible that asynchronously scheduled setTimeout
will be triggered one millisecond earlier, while average delay will be equal to specified delay or higher.
In order for this behaviour to be compensated, it could be:
const wait = delay => new Promise(resolve => setTimeout(resolve, ++delay));
In case a delay is needed to test asynchronous code, timer mocks can be used to fast-forward a timer.
Upvotes: 1
Reputation: 138457
I would assume that this is rather due to performance.now()
inaccuracy.
Upvotes: 2