Skip to content

Commit

Permalink
feat(utils): sleep fn
Browse files Browse the repository at this point in the history
  • Loading branch information
tsa96 committed Dec 21, 2024
1 parent 3644d70 commit 808aa55
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 0 deletions.
1 change: 1 addition & 0 deletions libs/util-fn/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,3 +16,4 @@ export * from './pick';
export * from './omit';
export * from './magic';
export * from './approx-eq';
export * from './sleep';
24 changes: 24 additions & 0 deletions libs/util-fn/src/sleep.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
import { sleep } from './sleep';

describe('sleep', () => {
it('resolves after the specified duration', async () => {
const start = Date.now();
await sleep(100);
const end = Date.now();
expect(end - start).toBeGreaterThanOrEqual(100);
});

it('resolves after a long duration', async () => {
const start = Date.now();
await sleep(1000);
const end = Date.now();
expect(end - start).toBeGreaterThanOrEqual(1000);
});

it('handles negative duration by resolving immediately', async () => {
const start = Date.now();
await sleep(-100);
const end = Date.now();
expect(end - start).toBeLessThan(10);
});
});
7 changes: 7 additions & 0 deletions libs/util-fn/src/sleep.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
export function sleep(duration: number): Promise<void> {
if (duration < 0) {
return Promise.resolve();
}

return new Promise((resolve) => setTimeout(resolve, duration));
}

0 comments on commit 808aa55

Please sign in to comment.