File tree Expand file tree Collapse file tree 2 files changed +40
-11
lines changed Expand file tree Collapse file tree 2 files changed +40
-11
lines changed Original file line number Diff line number Diff line change 1- import { sleep } from "./sleep.function" ;
1+ import { busyWaitForNanoSeconds , sleep } from "./sleep.function" ;
22
33describe ( "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} ) ;
Original file line number Diff line number Diff line change 11export 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+ } ;
You can’t perform that action at this time.
0 commit comments