Skip to content

Commit c0282de

Browse files
committed
(#85) Added higher resolution wait
1 parent d192ced commit c0282de

File tree

2 files changed

+40
-11
lines changed

2 files changed

+40
-11
lines changed

lib/sleep.function.spec.ts

Lines changed: 27 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,32 @@
1-
import { sleep } from "./sleep.function";
1+
import {busyWaitForNanoSeconds, sleep} from "./sleep.function";
22

33
describe("sleep", () => {
4-
it("should resolve after x ms", async () => {
5-
// GIVEN
6-
const timeout = 500;
4+
it("should resolve after x ms", async () => {
5+
// GIVEN
6+
const timeout = 500;
77

8-
// WHEN
9-
const before = Date.now();
10-
await sleep(timeout);
11-
const after = Date.now();
8+
// WHEN
9+
const before = Date.now();
10+
await sleep(timeout);
11+
const after = Date.now();
1212

13-
// THEN
14-
expect(after - before).toBeGreaterThanOrEqual(timeout);
15-
});
13+
// THEN
14+
expect(after - before).toBeGreaterThanOrEqual(timeout);
15+
});
16+
});
17+
18+
describe("busyWaitForNanoSeconds", () => {
19+
it("should resolve after x ns", async () => {
20+
// GIVEN
21+
const timeoutNs = 5000;
22+
const timeoutMs = 5;
23+
24+
// WHEN
25+
const before = Date.now();
26+
await busyWaitForNanoSeconds(timeoutNs);
27+
const after = Date.now();
28+
29+
// THEN
30+
expect(after - before).toBeGreaterThanOrEqual(timeoutMs);
31+
});
1632
});

lib/sleep.function.ts

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,16 @@
11
export const sleep = async (ms: number) => {
22
return new Promise(resolve => setTimeout(resolve, ms));
33
};
4+
5+
export const busyWaitForNanoSeconds = (duration: number) => {
6+
return new Promise(res => {
7+
const start = process.hrtime.bigint();
8+
let isWaiting = true;
9+
while (isWaiting) {
10+
if ((process.hrtime.bigint() - start) > duration) {
11+
isWaiting = false;
12+
}
13+
}
14+
res();
15+
});
16+
};

0 commit comments

Comments
 (0)